var $j = jQuery.noConflict();

var editor = null;

var BrowserDetect = {
	init: function () {this.browser = this.searchString(this.dataBrowser) || "An unknown browser"; this.version = this.searchVersion(navigator.userAgent)|| this.searchVersion(navigator.appVersion)|| "an unknown version";this.OS = this.searchString(this.dataOS) || "an unknown OS";if (this.browser + this.version == "Explorer6")this.ie6 = true;else if (this.browser + this.version == "Explorer7")this.ie7 = true;else if (this.browser == "Firefox")this.ff = true;else if (this.browser == "Opera")this.op = true;else if (this.browser == "Safari")this.safari = true;},
	searchString: function (data) {for (var i=0;i<data.length;i++){var dataString = data[i].string;var dataProp = data[i].prop;this.versionSearchString = data[i].versionSearch || data[i].identity;if (dataString) {if (dataString.indexOf(data[i].subString) != -1)return data[i].identity;}else if (dataProp)return data[i].identity;}},
	searchVersion: function (dataString) {var index = dataString.indexOf(this.versionSearchString);if (index == -1) return;return parseFloat(dataString.substring(index+this.versionSearchString.length+1));},
	dataBrowser: [{string: navigator.userAgent,subString: "OmniWeb",versionSearch: "OmniWeb/",identity: "OmniWeb"},{string: navigator.vendor,subString: "Apple",identity: "Safari"},{prop: window.opera,identity: "Opera"},{string: navigator.vendor,subString: "iCab",identity: "iCab"},{string: navigator.vendor,subString: "KDE",identity: "Konqueror"},{string: navigator.userAgent,subString: "Firefox",identity: "Firefox"},{string: navigator.vendor,subString: "Camino",identity: "Camino"},{string: navigator.userAgent,subString: "Netscape",identity: "Netscape"},{string: navigator.userAgent,subString: "MSIE",identity: "Explorer",versionSearch: "MSIE"},{string: navigator.userAgent,subString: "Gecko",identity: "Mozilla",versionSearch: "rv"},{string: navigator.userAgent,subString: "Mozilla",identity: "Netscape",versionSearch: "Mozilla"}],
	dataOS : [{string: navigator.platform,subString: "Win",identity: "Windows"},{string: navigator.platform,subString: "Mac",identity: "Mac"},{string: navigator.platform,subString: "Linux",identity: "Linux"}]};

BrowserDetect.init();

function resize(idObject) {
	var arrSizes = getPageSize();
	setSiteHeight(arrSizes.sizeContent,arrSizes.sizePage,idObject);
}

function getPageSize() {
	var sizeContent;
	var sizePage;
	var browserVersion = BrowserDetect.browser + BrowserDetect.version;
	
	if (BrowserDetect.ie6) {
		sizeContent = document.documentElement.scrollHeight;
		sizePage = document.documentElement.offsetHeight-5;		
	} else if (BrowserDetect.ie7) {
		sizeContent = document.documentElement.scrollHeight;
		sizePage = document.documentElement.offsetHeight;
	} else if (browserVersion == 'Explorer8'){
		sizeContent = document.documentElement.scrollHeight;
		sizePage = document.documentElement.offsetHeight;
	} else{
		sizeContent = document.documentElement.offsetHeight;
		sizePage = window.innerHeight;
	}
	
	return {sizeContent: sizeContent, sizePage: sizePage};
}

function setSiteHeight(sizeContent, sizePage, idObject){
	if (sizePage > sizeContent){
		if (BrowserDetect.ie6)
			$j("#"+idObject).height((sizePage) + "px");
		else
			$j("#"+idObject).css("min-height",(sizePage) + "px");
	}
}

$j(document).ready(function(){
	/*
	if(!browserBlock){
		if (!BrowserDetect.ff && !BrowserDetect.ie6 && !BrowserDetect.ie7 && !BrowserDetect.safari && !BrowserDetect.op){
			if(BrowserDetect.browser != 'Mozilla'){
				location.href = BASE_URL+'login/browserBlock';
			}
		}
	}
	*/
	$j(".colorPicker").colorPicker();
	
	$j("span.img_usuario").hover(
		function(){$j('div.editarImagem').slideDown(300);},
		function(){$j('div.editarImagem').slideUp(300);}
	);
	
	$j("span.img_usuario").bind('click', function(){
		openWindow('Alterar imagem', BASE_URL+'login/alterarImagem', 450, 150);
	});
	resize("conteudo");
	if(typeof(returnJSON) == 'undefined'){
		$j.ajaxSetup({
			global: false,
			dataType: "json",
			beforeSend: function(){
				$j('#carregando').show();
			},
			complete: function(){
				$j('#carregando').hide();
			}
		});
	}
	$j().ajaxStart(function() { $j('#carregando').show(); });
	$j().ajaxStop(function() { $j('#carregando').hide(); });	
	try{init();}catch(err){}
	editor = new nicEditor({iconsPath : BASE_URL +'img/nicEditorIcons.gif'});
	
});

function resizeGrid(idObject){
	var heightGrid;
	if(BrowserDetect.ie6){
		heightGrid = ((document.getElementById("conteudo").offsetHeight - document.getElementById(idObject).offsetTop) - 3) - document.getElementById(idObject).offsetTop;		
	}else{
		heightGrid = (document.getElementById("conteudo").offsetHeight - 3) - document.getElementById(idObject).offsetTop;		
	}
		
	document.getElementById(idObject).style.height= heightGrid + "px";
}

function alteraGrupo(url){
	var siteURL = url.split("chr", 2)[0];
	var externo = url.split("chr", 2)[1];
	if(externo == 'S')
		window.open(siteURL, '_blank');
	else
		location.href = siteURL;
}

function alteraPeriodo(url){location.href = url;}

function openWindow(name,pagina,w,h){
	var win = new Window('popUp', {className: "window", title: name, url: pagina, width:w, height:h, minimizable: false, maximizable: false, draggable: true, resizable: false, zIndex: 5});
	win.content.scrolling = 'no';
	win.showCenter(true);
	win.setDestroyOnClose();
	Windows.register(win);
}

function focusBtnMessageOk(){document.getElementById("btnMessageOk").focus();}

function messageBox(msg, w, h, field, functionCallback){
	Dialog.alert(msg, {windowParameters: {onShow: focusBtnMessageOk, className: "window", width:w, height:h, title: "Alerta", draggable: true, zIndex: 5}, okLabel: "Ok", buttonClass:"", ok:function(win) {callbackWindows(field,functionCallback); return true;}});				
}

function callbackWindows(data,functionCallback){
	if ($j.isFunction(data)){
		data();
	}else if(data != undefined){
		document.getElementById(data).style.visibility = 'visible';
		var parent = document.getElementById(data);
    	var tabIndex = getParentField(parent);
		tabPanel.setSelectedIndex(tabIndex);
		parent.focus();
	}
		
	if ($j.isFunction(functionCallback))
		functionCallback();
	
	return true;
}

function messageBoxLogin(msg, w, h, field, functionCallback){
	Dialog.alert(msg, {windowParameters: {onShow: focusBtnMessageOk, className: "window", width:w, height:h, title: "Alerta", draggable: true, zIndex: 5}, okLabel: "Ok", buttonClass:"", ok:function(win) {callbackWindowsLogin(field,functionCallback); return true;}});				
}

function callbackWindowsLogin(data,functionCallback){
	if ($j.isFunction(data)){
		data();	
	}  else if(data != undefined){
		var parent = document.getElementById(data);
		parent.focus();
	}
		
	if ($j.isFunction(functionCallback))
		functionCallback();
	
	return true;
}

function messageConfirm(msg, w, h, functionCallBack){
	Dialog.confirm(msg, {onShow: focusBtnMessageOk, className: "window", title: "Confirma", width:w, height:h, okLabel: "Sim", cancelLabel: "Não", draggable: true, zIndex: 5, buttonClass: "",  cancel:function(win) {callBackNao(functionCallBack); return true;}, ok:function(win) {callBackSim(functionCallBack); return true;}});	
}

function callBackSim(functionCallBack){functionCallBack(true);}

function callBackNao(functionCallBack){functionCallBack(false);}

var formDatas = new Array;

function ajaxFormPush(form){   		
	jsonData = $j("#"+form).formToArray();
	if(jsonData) {
		for (var n in jsonData)
	    	formDatas.push(jsonData[n]);
	}
}

function resetForm(form){$j("#"+form).resetForm();}

function clearFields(form){$j("#"+form).clearFields();}
 
//TODO 'i = 22' - colocar algo do tipo 'parent.element = "body"'
//TODO deixei com i = 22 pq acho isso muito engraçado, n sei pq ta funcionando
function getParentField(parent){
    var i = 0;
	while ((parent.className != 'tab-page' || i == 22)){
		parent = parent.parentNode;
		i++;
	}
    return parent.id;
}

function beforeSubmit(formData, jqForm, options, formName){
	var submit = true;
	var textEditors = document.getElementsByTagName('textarea');
	for(var i = 0; i < formData.length; i++){
		for (var j = 0; j < textEditors.length; j++) {
			if (textEditors[j].className == 'textEditor'){
				if(textEditors[j].id == formData[i].name){
					editor.panelInstance(textEditors[j].id);
					formData[i].value = document.getElementById(textEditors[j].id).value;
				}
			}
		}
	}
	
	if(formName != 'formLogin'){
		$j.post(BASE_URL+'login/validaAutenticacaoAjax',
			function(data){
				if(!data.logged.message){
					window.alert('Execute novamente o login no sistema.');
					submit = false;
				}
			}
		);
	}	
	
	return submit;
}

function random(){return new Date().getTime();}

function montaCombo(cmbName,url,param,selectedIndex,functionCallback){
	objectCombo = document.getElementById(cmbName);
	countRows = objectCombo.length;
	for(var j = objectCombo.length; j > 0 ; j--){
		objectCombo.remove(j);
	}

	if(param != undefined){
		//TODO POR O REPLACE
		paramSelectedIndex = param + "";
		if(paramSelectedIndex.substr(0,1) != "{")
			selectedIndex = param;
	}
	
	$j.post(url, param, function(data){
		for(var i = 0 ; i < data.montaCombo.length ; i++) {
			var value      =  data.montaCombo[i].value;
			var optionName =  data.montaCombo[i].optionName;

		    if(optionName!=false)
		       objectCombo.options[objectCombo.options.length] = new Option (optionName, value, true, true);
		}
		if(selectedIndex != undefined)
			objectCombo.value = selectedIndex;
		else
			objectCombo.value = "";
			
		if ($j.isFunction(functionCallback))
			functionCallback();
	}, 'json');
}

var keyEvent = 'keypress';
if(BrowserDetect.ie7 || BrowserDetect.ie6){keyEvent='keydown';}
shortcut.add("Ctrl+S", function(evt) { try{salvar();}catch(err){ } }, {'type':keyEvent,'propagate':false,'target':document});
shortcut.add("Ctrl+N", function(evt) { try{novo();}catch(err){ } }, {'type':keyEvent,'propagate':false,'target':document});
shortcut.add("Ctrl+X", function(evt) { try{excluir();}catch(err){ } }, {'type':keyEvent,'propagate':false,'target':document});
shortcut.add("Ctrl+P", function(evt) { try{imprimir();}catch(err){ } }, {'type':keyEvent,'propagate':false,'target':document});

function trim(str){return str.replace(/^\s+|\s+$/g,"\n");}

/*
CSS Browser Selector v0.2.7
Rafael Lima (http://rafael.adm.br)
http://rafael.adm.br/css_browser_selector
License: http://creativecommons.org/licenses/by/2.5/
Contributors: http://rafael.adm.br/css_browser_selector#contributors
*/
var css_browser_selector = function() {var ua=navigator.userAgent.toLowerCase(),is=function(t){return ua.indexOf(t) != -1;},h=document.getElementsByTagName('html')[0],b=(!(/opera|webtv/i.test(ua))&&/msie (\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?'gecko ff2':is('firefox/3')?'gecko ff3':is('gecko/')?'gecko':is('opera/9')?'opera opera9':/opera (\d)/.test(ua)?'opera opera'+RegExp.$1:is('konqueror')?'konqueror':is('applewebkit/')?'webkit safari':is('mozilla/')?'gecko':'',os=(is('x11')||is('linux'))?' linux':is('mac')?' mac':is('win')?' win':'';var c=b+os+' js'; h.className += h.className?' '+c:c;}();

function faleConosco(){
	openWindow('Fale Conosco', BASE_URL+'cadastrosDiversos/faleConosco', 590, 353);
}

function closeWindows(){
	Windows.closeAllModalWindows();
}

function exibeQuestionario(idQuestionario, titulo){
	openWindow(titulo, BASE_URL+'questionarios/questionario/responder/'+idQuestionario, 700, 500);
}

function ajudeSantaCatarina(){
	openWindow('Santa Catarina Urgente', BASE_URL+'cadastrosDiversos/ajudeSantaCatarina', 500, 163);
}