// JavaScript Document

//inicialização jQuery

$(document).ready(function(){
	

	//BTN Design
	btnDesign()
	
		
	//Deve ser chamado por ultimo pq chama outros scripts
	//Executa UIS
	wljsData()
	wljsSpinner()
	wljsTooltip()
	
	//flip
	wljsFlip()
	
	//sortable
	wljsSortable()
	
	//Dialog
	 wljsDialog()
	 
	 //Dialog
	 wljsYoutube()
	
}); //fecha onReady


/*JQUERY UI*/
//wl_data
	function wljsLoadUIWidget(widget){
		var scriptsToLoad =new Array()
		
		//basicos para ui
	
		scriptsToLoad.push('../css2/jqueryui/minified/jquery.ui.core.min.js')
		scriptsToLoad.push('../css2/jqueryui/minified/jquery.ui.widget.min.js')
		
	if(widget=="datepicker"){scriptsToLoad.push('../css2/jqueryui/minified/jquery.ui.datepicker.min.js')}
	if(widget=="spinner"){scriptsToLoad.push('../css2/jqueryui/minified/jquery.ui.spinner.min.js','../css2/jqueryui/minified/jquery.ui.button.min.js')}
	if(widget=="dialog" || widget=="modal"){scriptsToLoad.push('../css2/jqueryui/minified/jquery.ui.position.min.js','../css2/jqueryui/minified/jquery.ui.dialog.min.js','../css2/jqueryui/minified/jquery.ui.mouse.min.js', '../css2/jqueryui/minified/jquery.ui.resizable.min.js', '../css2/jqueryui/minified/jquery.ui.draggable.min.js')}
	if(widget=="tooltip"){scriptsToLoad.push('../css2/jqueryui/minified/jquery.ui.position.min.js','../css2/jqueryui/minified/jquery.ui.tooltip.min.js')}
	if(widget=="flip"){scriptsToLoad.push('../css2/jqueryui/minified/jquery.effects.core.min.js','../css2/jqueryui/minified/jquery.flip.min.js')}	
	
	if(widget=="sortable"){scriptsToLoad.push('../css2/jqueryui/minified/jquery.ui.mouse.min.js','../css2/jqueryui/minified/jquery.ui.draggable.min.js','../css2/jqueryui/minified/jquery.ui.sortable.min.js')}
		
		//chama os scripts, só funciona no site
		wljsLoadScript(scriptsToLoad)
		
		
		}//fechawljsLoadUIWidget




	function wljsData(){
		//checa se existe o .wl_data	
		if ($(".wl_data").length){
		
		//carrega os scripts necessarios			
		wljsLoadUIWidget('datepicker')
		
		//DATEPICKER para portugues
		// CONFIGURAÇÃO DO DATEPICKER DO JQUERYUI PARA PT-BR
			$.datepicker.setDefaults({dateFormat: 'dd/mm/yy',
									  dayNames: ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado','Domingo'],
									  dayNamesMin: ['D','S','T','Q','Q','S','S','D'],
									  dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb','Dom'],
									  monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro', 'Outubro','Novembro','Dezembro'],
									  monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set', 'Out','Nov','Dez'],
									  nextText: 'Próximo',
									  prevText: 'Anterior'
									 });
			
				//executa	
				$( ".wl_data" ).datepicker();	
					
			}
		
	}//Fecha wljsData
	
	function wljsSpinner(){
	
		
		//checa se existe o .wl_spinner
		if ($(".wl_spinner").length){
			
			//carrega os scripts necessarios			
			wljsLoadUIWidget('spinner')
			//executa
			//ainda nao  funciona
			$(".wl_spinner").spinner();		
		}
	}//Fecha wljsSpinner
	
		function wljsTooltip(){
	
		
		//checa se existe o .wl_tooltip
		if ($(".wl_tooltip").length){
			
			//carrega os scripts necessarios			
			wljsLoadUIWidget('tooltip')
			//executa			
			$(".wl_tooltip").tooltip();	
			
				
		}
	}//Fecha wljsTooltip
	
	//http://lab.smashup.it/flip
	//http://tutorialzine.com/2010/03/sponsor-wall-flip-jquery-css/
	function wljsFlip(){
		//checa se existe o .wl_data	
		if ($(".wl_flip").length){
		
		//carrega os scripts necessarios			
		wljsLoadUIWidget('flip')
		
	
				
	/* The following code is executed once the DOM is loaded */
					//mouseenter mouseleave
					$('.wl_flip').bind("click",function(){
				
						// $(this) point to the clicked .sponsorFlip element (caching it in elem for speed):
				
						var elem = $(this);
				
						// data('flipped') is a flag we set when we flip the element:
				
						if(elem.data('flipped'))
						{
							// If the element has already been flipped, use the revertFlip method
							// defined by the plug-in to revert to the default state automatically:
				
							elem.revertFlip();
				
							// Unsetting the flag:
							elem.data('flipped',false)
						}
						else
						{
							// Using the flip method defined by the plugin:
				
							elem.flip({
								direction:'lr',
								speed: 350,
								color: '#fff',
								content: $(this).attr("title"),
								onBefore: function(){
									// Insert the contents of the .sponsorData div (hidden
									// from view with display:none) into the clicked
									// .sponsorFlip div before the flipping animation starts:
				
									//elem.html(elem.siblings('.sponsorData').html());
								}
							});
				
							// Setting the flag:
							elem.data('flipped',true);
						}
					});
				
			
				
				
				
					
			}
		
	}//Fecha wljsflip
	
	
//só funciona em site 
var cacheScriptsArray=new Array()

function checaCacheScripts(urlScript){
	
//	console.log('Url Script: '+urlScript)
	
	var scriptNExiste=true
	
	//alert(urlScript)
	
	for(var i=0;cacheScriptsArray.length>i;i++){
		//alert(cacheScriptsArray[i])
		if(cacheScriptsArray[i]==urlScript){
			
			scriptNExiste=false
		}
	}
	
	//Se nao existe adicona na array
	if(scriptNExiste){cacheScriptsArray.push(urlScript);}
	
	
	return scriptNExiste
}


function wljsLoadScript(urlArray){
	
	var objScripts= new Object()
	
	//Se passar apenas 1 fica como apenas oelemento 1, se passar váriosfica no objeto
	if(typeof(urlArray)=='object'){
		objScripts=urlArray
	}else{
		objScripts[0]=urlArray	
	}
	
	for(var i=0;objScripts.length>i;i++){
		//console.log("i: "+ i + "scripts a serem carregados: " + objScripts)
		//console.log("Veturn : "+checaCacheScripts(objScripts[i]))
		
		//console.log(objScripts[i])
		//checa se o scriptjá foi carregado
		if(checaCacheScripts(objScripts[i])){
			$.ajax({
				  url: objScripts[i],
				  async:false,
				  cache:false,
				  dataType: "script",
				  success: function( data ){
						//  if(onSuccess!='undefined'){
						//  onSuccess(data)
						//  }
					//  alert("script:  " + objScripts[i])
				  },
				  error:function (xhr, ajaxOptions, thrownError){
							//console.log(xhr.status);
							//console.log(thrownError);
						} 
				  //complete: function( data ){alert('complete')}
				});
		}//fecha if
		
		
	}//fecha form
  
}//fecha wljsLoadScript


/*BTN DESIGN*/
function btnDesign(){
	//tamanho da imagem a ser colocado no botao
	var maxImgSize=32
	
	$(".btn2").each(function(index, element) {
				
		var ImgSizeHeight=$(this).prev("img").height()
		var ImgSizeWidth=$(this).prev("img").width()
		
		
		
		//executa funcao de substituição se o tamanho for menor que o permitido, e a houver uma imagem antes da tag $(this).prev("img") != null
		if(	ImgSizeHeight<=maxImgSize && ImgSizeWidth<=maxImgSize && $(this).prev("img").is('img') ){
			
			 
			//pega o source da imagem
			var srcImagem = $(this).prev("img").attr('src')
			//remove a imagem
			$(this).prev("img").remove()
			
			//aplica ao fundo do botao a imagem
			//srcImagem
			
			//pergunta se já tem estilo aplicato no botao, se tiver soma, senão comeca com vazio
			if($(this).attr('style')==undefined){
				var estiloBotao=''
			}else{
				var estiloBotao =$(this).attr('style')
			}
			
			estiloBotao +='background-image: url('+srcImagem+');'
		//	estiloBotao +='background-repeat: no-repeat;'
		//	estiloBotao +='background-position: 5px center;'
			
			//$(this).attr('style', 'background-image: url('+srcImagem+');')
			$(this).attr('style', estiloBotao)
			
			$(this).addClass('icone')
			
			
			/*background-image: url(css_images/bt_fundo.gif);
			background-color: #F0F0F0;
			background-repeat: no-repeat;
			background-position: 0px center;*/
					
		}
		
      
    });	
}




//Funcao de drag and drop no ul
function wljsSortable(){
	
		//checa se existe o .wl_spinner
		if ($(".wl_sortable").length){
			
			//carrega os scripts necessarios			
			wljsLoadUIWidget('sortable')
			
			//executa
			
				$(".wl_sortable").sortable({
				revert: true,
				connectWith: ".wl_sortable_conect"
			})
			
			//Codigo para execução depois que para o sort
				/*	$(".wl_sortable").bind("sortstop",function(){				
			   alert('oi')
			})*/
		}//fecha if
	
}//fecha sortable

//Funcao de drag and drop no ul
function wljsDialog(){
	
		//checa se existe o .wl_spinner
		if ($(".wl_dialog").length){
			
			//carrega os scripts necessarios			
			wljsLoadUIWidget('dialog')
			
			//executa
			
			$(".wl_dialog").each(function(index, element) {
               
			    if($(this).attr("ref")!=undefined){
					$(".wl_dialog").click(function(e) {
                        $($(this).attr("ref")).dialog({ autoOpen: true })
                    });//end click
					
				}//end if
				
            });//end each
			
				//$(".wl_dialog").dialog({ autoOpen: false })
			
		}
	
}//fecha sortable

//Funcao youtube pelo link 
function wljsYoutube(){
	
		//checa se existe o .wl_spinner
		if ($(".wl_youtube a").length){
			
			var tempArray= new Array("../css2/plugins/youtubin/jquery.youtubin.js")
			//chama os scripts, só funciona no site
		wljsLoadScript(tempArray)
			
			//executa
			
			$(".wl_youtube a").each(function(index, element) {
               
			   /* if($(this).attr("ref")!=undefined){
					$(".wl_dialog").click(function(e) {
                        $($(this).attr("ref")).dialog({ autoOpen: true })
                    });//end click
					
				}//end if*/
				$(this).youtubin();
				
				
            });//end each
			
				//$(".wl_dialog").dialog({ autoOpen: false })
			
		}
	
}//fecha youtubin

/*Funcoes antigas do spry*/

//monta a string get ao para ser enviado para o servidor
	function wl_objectGET(myobject, myrandom){
		var myGetParams= new String()		
		for (var propertyName in myobject) {
			//propertyName = nome do atributo do objeto // myobject[propertyName] = valor do atributo
			myGetParams+= propertyName + '=' + myobject[propertyName] + '&';
		}
		// se random for true adiciona um parametro randomico para evitar cache
		if(myrandom | myrandom=='random'){myGetParams+= wl_randomNumber()}
		
		//usa o a funcao wl_formResult
		
		//retorna o valor do get montado
		return(myGetParams)
	}

	//Pega um formulario pelo seu id e retorna os valores dos inputs na forma de um objeto
	function wl_formResult (form) {
		var form_element = document.getElementById(form);
		var form_element_array = getElementsByTagNames('input,select,textarea',form_element); //chama a  funcao getElementsByTagNames
	
		var obj_wl_formResult= new Object()
		for(var i=0; i<form_element_array.length; i++){
			
			if(form_element_array[i].type=='radio'){
				//alert('id:'+ form_element_array[i].id + '   checked: ' + form_element_array[i].checked)
				if(form_element_array[i].checked){
				obj_wl_formResult[form_element_array[i].id]=form_element_array[i].value;
				}
			}else{			
				obj_wl_formResult[form_element_array[i].id]=form_element_array[i].value;
			}
		};
			return(obj_wl_formResult)	
	};

