var xmlHttp;
var sent = false;
var debug = false;
var fulldebug = false;
var t;
var goodMsg = "&iexcl; Gracias por comunicarse !";
var data; // inicializa los campos que van a ser parceados
var redireccion; // inicializa redireccion por si se pide del post
var loadingMsg = "Cargando... Enviando... Espere unos segundos...";
var sendingMsg = "Enviando...";
var successMsg = '<a href="#" style="color:#fff;">Mensaje Enviado!</a>';
var badMsg = "Verifique los campos marcados en rojo";
var NOPOSTS = '<b style="font-size: 200%;">No se han encontrado entradas.</b>';
var _SPEED_FADEOUT = 500;
var _SPEED_FADEIN = 500;	
var lastSearch = '';
var actualContent = '';
var inner = '';

// VIDEO
function showVideo1(object) {
	if($('#slide_campanias').is(':visible')) {
		$('#slide_campanias').hide();
		$('#video_player').show();
	}
}

// VIDEO
function hideVideo1(object) {
	if($('#slide_campanias').is(':hidden')) {
		$('#slide_campanias').show();
		$('#video_player').hide();
	}
}


function showVideo(object) {
	if($('#slide_campanias-2').is(':visible')) {
		$('#slide_campanias-2').hide();
		$('#video_player-3').show();
	}
}

// VIDEO
function hideVideo(object) {
	if($('#slide_campanias-2').is(':hidden')) {
		$('#slide_campanias-2').show();
		$('#video_player-3').hide();
	}
}

// JQUERY -----------------------------------------------------------------------------
$(function() {

// CYCLE HOME
$('#slide').cycle({
fx:     'fade',
speed:   1000,
timeout: 4000,
prev:   '.siguiente',
next:   '.anterior'
});
//$('#slide').cycle('pause');

// CYCLE CAMPANIAS CON MAS DE 1 VIDEO
$('#slide_campanias-2').after('<ul class="col-3" id="col-3-pager">').cycle({
fx:     'fade',
speed:   'fast', 
timeout: 0, 
pager:  '#col-3-pager',
pagerEvent: 'mouseover',
pagerAnchorBuilder: function(idx, slide) {
return '<li id="id_'+idx+'"><a href="#" onclick="hideVideo(this)" title=""><img src="'+slide.src+'.thumb.jpg" alt="" width="75" height="64" /></a></li>'; 
}
});
$('#col-3-pager').append('<li><a href="#" onclick="showVideo(this)" title=""><img src="'+root+'img/video_campania.jpg" alt="" width="75" height="64" /></a></li>');


// CYCLE CAMPANIAS CON 1 VIDEO
$('#slide_campanias').after('<ul class="col-3" id="col-3-pager">').cycle({
fx:     'fade',
speed:   'fast', 
timeout: 0, 
pager:  '#col-3-pager',
pagerEvent: 'mouseover',
pagerAnchorBuilder: function(idx, slide) {
return '<li id="id_'+idx+'"><a href="#" onclick="hideVideo(this)" title=""><img src="'+slide.src+'.thumb.jpg" alt="" width="75" height="64" /></a></li>'; 
}
});
$('#col-3-pager').append('<li><a href="#" onclick="showVideo(this)" title=""><img src="'+root+'img/video_campania.jpg" alt="" width="75" height="64" /></a></li>');



// CYCLE CAMPANIAS SIN VIDEO
$('#slide_campanias_sin_video').after('<ul class="col-3" id="col-3-pager">').cycle({
fx:     'fade',
speed:   'fast', 
timeout: 0, 
pager:  '#col-3-pager',
pagerEvent: 'mouseover',
pagerAnchorBuilder: function(idx, slide) {
return '<li id="id_'+idx+'"><a href="#" onclick="hideVideo(this)" title=""><img src="'+slide.src+'.thumb.jpg" alt="" width="75" height="64" /></a></li>'; 
}
});

// CYCLE PRODUCTOS
$('.prod_ampliado').after('<div class="vistas" id="visitas_contenedor">').cycle({
fx:     'fade',
speed:   'fast', 
timeout: 0, 
pager:  '.vistas',
pagerAnchorBuilder: function(idx, slide) {
return '<a href="#" title=""><img src="'+slide.src+'&amp;w=90&amp;h=70&amp;zc=1" alt="" width="90" height="70" /></a>';
}
});

// SIFR
//<![CDATA[
if(typeof sIFR == "function"){
	sIFR.replaceElement(named({sSelector:"#buscador label", sFlashSrc:root+"titulos/h.swf", sColor:"#cccccc",  /*nPaddingRight:"8",sFlashVars:"textalign=right",  nPaddingRight:"23", sLinkColor:"#0099ff", sBgColor:"#000000", sHoverColor:"#0099ff", nPaddingTop:20, nPaddingBottom:20, sFlashVars:"textalign=center&amp;offsetTop=6",*/ sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"#columnas h3", sFlashSrc:root+"titulos/h.swf", sColor:"#cc0000",/*sFlashVars:"textalign=right",  nPaddingRight:"23", sLinkColor:"#0099ff", sBgColor:"#000000", sHoverColor:"#0099ff", nPaddingTop:20, nPaddingBottom:20, sFlashVars:"textalign=center&amp;offsetTop=6",*/ sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"#columnas h4", sFlashSrc:root+"titulos/h.swf", sColor:"#666666",/*sFlashVars:"textalign=right",  nPaddingRight:"23", sLinkColor:"#0099ff", sBgColor:"#000000", sHoverColor:"#0099ff", nPaddingTop:20, nPaddingBottom:20, sFlashVars:"textalign=center&amp;offsetTop=6",*/ sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"#slide h2", sFlashSrc:root+"titulos/h.swf", sColor:"#ffffff", sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"#slide span", sFlashSrc:root+"titulos/h.swf", sColor:"#cc0000", sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"#titulo h2", sFlashSrc:root+"titulos/h2.swf", sColor:"#ffffff",/*sFlashVars:"textalign=right",  nPaddingRight:"23", sLinkColor:"#0099ff", sBgColor:"#000000", sHoverColor:"#0099ff", nPaddingTop:20, nPaddingBottom:20, sFlashVars:"textalign=center&amp;offsetTop=6",*/ sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"#titulo h3", sFlashSrc:root+"titulos/h.swf", sColor:"#cc0000",/*sFlashVars:"textalign=right",  nPaddingRight:"23", sLinkColor:"#0099ff", sBgColor:"#000000", sHoverColor:"#0099ff", nPaddingTop:20, nPaddingBottom:20, sFlashVars:"textalign=center&amp;offsetTop=6",*/ sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"#producto-ampliado h4", sFlashSrc:root+"titulos/h2.swf", sColor:"#cc0000",/*sFlashVars:"textalign=right",  nPaddingRight:"23", sLinkColor:"#0099ff", sBgColor:"#000000", sHoverColor:"#0099ff", nPaddingTop:20, nPaddingBottom:20, sFlashVars:"textalign=center&amp;offsetTop=6",*/ sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"#content-empresa h4", sFlashSrc:root+"titulos/h2.swf", sColor:"#cc0000",/*sFlashVars:"textalign=right",  nPaddingRight:"23", sLinkColor:"#0099ff", sBgColor:"#000000", sHoverColor:"#0099ff", nPaddingTop:20, nPaddingBottom:20, sFlashVars:"textalign=center&amp;offsetTop=6",*/ sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"#form-trabaja h3", sFlashSrc:root+"titulos/h2.swf", sColor:"#cc0000",/*sFlashVars:"textalign=right",  nPaddingRight:"23", sLinkColor:"#0099ff", sBgColor:"#000000", sHoverColor:"#0099ff", nPaddingTop:20, nPaddingBottom:20, sFlashVars:"textalign=center&amp;offsetTop=6",*/ sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"#form-contacto h3", sFlashSrc:root+"titulos/h2.swf", sColor:"#cc0000",/*sFlashVars:"textalign=right",  nPaddingRight:"23", sLinkColor:"#0099ff", sBgColor:"#000000", sHoverColor:"#0099ff", nPaddingTop:20, nPaddingBottom:20, sFlashVars:"textalign=center&amp;offsetTop=6",*/ sWmode:"transparent"}));
};
//]]>

// FADE BANNERS HOME
$('#columnas img').hover(function(){$(this).animate({opacity:0.6},100,'linear');},function(){$(this).animate({opacity:1.0},100,'linear');});
// FADE BULLET NEW LISTADOS
$('.new').hover(function(){$(this).animate({opacity:0.3},100,'linear');},function(){$(this).animate({opacity:1.0},100,'linear');});
$('.img').hover(function(){$(this).animate({opacity:0.7},100,'linear');},function(){$(this).animate({opacity:1.0},100,'linear');});
$('.new_big').hover(function(){$(this).animate({opacity:0.3},300,'linear');},function(){$(this).animate({opacity:1.0},300,'linear');});

// MENU
// hide contenedor_menu on mouseleave
//$('#contenedor_menu').mouseleave(
//function(){
//$('.sub_menu_contenedor').hide();
//$('.sub_sub_menu_contenedor').hide();
//});

// SHOW CAT MENU, HIDE TODO
$(".sub_menu_contenedor").hide();
$('.sub_sub_menu_contenedor').hide();
$('#nav .productos > a').hover(
function(){
$('.sub_menu_contenedor').show();
sIFR.replaceElement(named({sSelector:"#header h3", sFlashSrc:root+"titulos/h2.swf", sColor:"#c3151e", sHoverColor:"#333333",/*sFlashVars:"textalign=right",  nPaddingRight:"23", sLinkColor:"#0099ff", sBgColor:"#000000", sHoverColor:"#0099ff", nPaddingTop:20, nPaddingBottom:20, sFlashVars:"textalign=center&amp;offsetTop=6",*/ sBgColor:"#ffffff"}));
},
function(){
});

// SHOW SUB CAT MENU
$('.sub_menu_item').hover(
function(){
$('.sub_sub_menu_contenedor').hide();
var id = $(this).attr('id');
$('#sub_'+id).show();	
},
function(){
});

$('.sub_sub_menu_contenedor').hover(
function(){
},
function(){
$('.sub_menu_contenedor').hide();
$('.sub_sub_menu_contenedor').hide();
});

// END JQUERY ----------------------------------------------------------------------------------------------
});

// ----------------- AJAX ------------------- //

var xmlHttp;
function GetXmlHttpObject(){var xmlHttp=null;try{xmlHttp=new XMLHttpRequest();}catch(e){try{xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}catch(e){xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}}return xmlHttp;}

///////////////////// POPUP ////////////////////////

// popup $.blockui
function popup(msg,fade,color){
$.blockUI({ 
message: msg.replace(/\n/gi,'<br/>'),
css: {
border:'none', padding:'15px', size:'12.0pt',
backgroundColor:'#900', color:'#000',
opacity:'.9','-webkit-border-radius': '10px','-moz-border-radius': '10px'
}
});

// DESBLOCKEAR BLOCK UI CON TIMEOUT ms //
var fade = 3000;
window.setTimeout($.unblockUI, fade);

// DESBLOCKEAR BLOCK UI CON CLICK //
//$(document).bind('click', function() {
//window.setTimeout($.unblockUI, 1);
//});

}

////////////////// COLOREA CAMPOS ///////////////////////////

// validate estilo de campos
function validate(status,id){
if(status == 0){
//document.getElementById(id).style.borderColor = '#f00';
//document.getElementById(id).style.color= '#f00';
$("#"+id).css('background','#ffe3e3');
$("#"+id).css('color','red');
$("#"+id).css('border','2px solid red');
//$("label[for="+id+"]").css('color','red');
//$('#todo_'+id).css('background','red');
}else{
//document.getElementById(id).style.borderColor = '#00ff00';
//document.getElementById(id).style.color= '#00ff00';
$("#"+id).css('background','#e3ffe8');
$("#"+id).css('color','green');
$("#"+id).css('border','2px solid green');
//$('#todo_'+id).css('background','transparent');
}
}

// ver multiple
function verMultiple(id){
var valor = getMultiple(id)
alert(valor);
}

//////////////////// PARSER /////////////////////////

// parser
function parseParams(params){
var contenedor = '';
for(var contar in params){
var type = gettype(params[contar]);
if(type == 'checkbox' || type == 'radio'){
contenedor += params[contar]+'='+getcheck(params[contar])+'&';
}else if(type == 'select-multiple'){
contenedor += params[contar]+'='+getMultiple(params[contar])+'&';
}else if(type == 'file'){
contenedor += params[contar]+'='+getArray(params[contar])+'&';
}
else{
contenedor += params[contar]+'='+escape(getval(params[contar]))+'&';
}
}
return contenedor.substr(0,contenedor.length-1);
}

// Get And Sets
function setval(id,val){
document.getElementById(id).value = val;
}
function getval(id){
return document.getElementById(id).value;
}
function getcheck(id){
return document.getElementById(id).checked;
}
function gettype(id){
return document.getElementById(id).type;
}
function getMultiple(ob){
ob = document.getElementById(ob);
selected = new Array();
for(var i = 0; i < ob.options.length; i++) if(ob.options[i].selected) selected.push(ob.options[i].value);
return selected;
}
function getArray(ob){
var el=document.getElementById(ob)
//alert(divElements.item(i));
//valores = new Array();
//for (var i = 0; i < ob.attributes.length; i++) if(ob.attributes[i].specified) valores.push(ob.attributes[i].nodeValue);
//return valores;
}

///////////////// REDIR ////////////////////////////

// redir
function redir(url,timeout){
	setTimeout('doRedir(\''+url+'\')',timeout);
}
// do redir
function doRedir(url){
	window.location = url;
}


// ------------------------------ //
// ------------------------------ //
// ------------------------------ //
// ------------------------------ //

function cargar(){
	if(document.getElementById('buscador_termino') != null){
		inner = document.getElementById('content').innerHTML;
		if(inner.trim() == ''){
			document.getElementById('content').innerHTML = NOPOSTS;
		}
		hide('close');
		hide('loading');
		show('unclose');
		document.getElementById('buscador_termino').value = '';
		inner = document.getElementById('content').innerHTML;
		actualContent = inner;
	}
}

function cerrar(){
	hide('close');
	hide('loading');
	show('unclose');
	lastSearch = '';
	document.getElementById('buscador_termino').value = '';
	jQuery('#content').slideUp(_SPEED_FADEOUT,function(){
		document.getElementById('content').innerHTML = actualContent;
		jQuery('#content').slideDown(_SPEED_FADEIN);
	});
}

function show(id){
	document.getElementById(id).style.display = 'block';
}
function hide(id){
	document.getElementById(id).style.display = 'none';
}
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

function buscar(){
	clearTimeout(t);
	t = setTimeout('buscar2();',500);
}

function buscar2(){
	var text = document.getElementById('buscador_termino').value;
	if(lastSearch.trim() == text.trim()) return;
	lastSearch = text;
	hide('unclose');
	hide('close');
	show('loading');

	if(text.trim() == ''){
			cerrar();
			return;
	}
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null){
		alert ('Tu explorador no soporta AJAX !');
		return;
	} 
	var params = "term="+text;
	xmlHttp.onreadystatechange = doSearch;
	xmlHttp.open("POST",root+"buscador.php",true);
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", params.length);
	xmlHttp.setRequestHeader("Connection", "close");
	xmlHttp.send(params);
} 

function doSearch(){ 
	if (xmlHttp.readyState==4){ 
		var r = xmlHttp.responseText;
		//alert(r);
		if(r.trim() == ''){
			r = NOPOSTS;
		}
		inner = document.getElementById('content').innerHTML;
		hide('loading');
		hide('unclose');
		show('close');
		
		if(r.trim() == inner.trim()) return;
		jQuery('#content').slideUp(_SPEED_FADEOUT,function(){
			document.getElementById('content').innerHTML = r;
			jQuery('#content').slideDown(_SPEED_FADEIN);
		});
	}
}

function validar(campos,mode,url,up){

	if(sent) return false;
	popup(loadingMsg);
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null){
		alert ('Tu explorador no soporta AJAX.');
		return;
	} 
	
	if(url) {
	redireccion = url;
	}else {
	redireccion = 0;
	}
		
	data = document.getElementById(campos).value;
	data = data.split(',');
	var params = parseParams(data);
	
	xmlHttp.onreadystatechange = doValidar;
	xmlHttp.open("POST",root+'admin/_plugins/ajax/validate.php?mode='+mode,true);
	xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xmlHttp.setRequestHeader("Content-length",params.length);
	xmlHttp.setRequestHeader("Connection", "close");
	xmlHttp.send(params);
}

function doValidar(){ 

var errores = 0;

	if (xmlHttp.readyState==4){
		
		//$('html, body').animate({scrollTop:0}, 1500);
	
		var r = xmlHttp.responseText;
		
		// debug
		if(debug == true) alert(r);
		if(debug == true && redireccion!=0) alert('redireccionar a la url: '+redireccion+' si es que todos los campos estan validados.');
		
		var x = 0;
		var f = new Array();
		
		for(i in data){
			f[x] = r.substr(x,1);
			
			// fulldebug
			if(fulldebug == true) alert('campo numero:'+f[x]);
			
			validate(f[x],data[i]);
			x++;
		}
		
		for(i in f){
			if(f[i] == '0') errores++;
		}
		
		// fulldebug
		if(fulldebug == true) alert('errores='+errores);
				
		if(errores > 0){
			popup(badMsg,true,"#f00");
		}else{
			sent = true;
			popup(sendingMsg,true);
			$('#ocultar-enviar').fadeOut('slow', function() {
			//$('#ocultar-enviar').html(successMsg).slideDown('slow');
			});
			$('#ocultar-enviar-otro').fadeOut('slow', function() {
			//$('#ocultar-enviar-otro').html(successMsg).slideDown('slow');
			});
			popup(successMsg,true);
			if(redireccion!=0) redir(redireccion,5000);
		}
	
	}

}

///////////////////////// REL ////////////////////

// show rel
function getColor(item_id,color_id){

document.getElementById('prod_ampliado_contenedor').innerHTML = '';
document.getElementById('visitas_contenedor').innerHTML = '';
document.getElementById('contenedor_colores').innerHTML = '';

xmlHttp=GetXmlHttpObject();
if (xmlHttp==null){
alert ('Tu explorador no soporta AJAX !');
return;
}

xmlHttp.onreadystatechange = function() {
	if (xmlHttp.readyState==4){	
	r = xmlHttp.responseText;
	r = r.split('+_+');
	//alert(r[0]);
	//alert(r[1]);
	//alert(r[2]);
	document.getElementById('prod_ampliado_contenedor').innerHTML = r[0];
	document.getElementById('visitas_contenedor').innerHTML = r[1];
	document.getElementById('contenedor_colores').innerHTML = r[2];
	}
}

xmlHttp.open("POST",root+"getColor.php?item_id="+item_id+"&color_id="+color_id,true);
xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(null);

}