
/************************ Mesa de Regalos ******************/
function swapText(input){
	input.value='';
}

function swapMessage(input){
	var intValue = stringToInt(input.value);
	if(intValue < 0){
		input.value='';
	}
}
/**
 * Valida que el valor introducido sea un entero
 * (si es decimal lo convierte al entero más proximo)
 * de lo contrario envia 0 a updateCart 
 * y coloca el mensaje en la caja de texto
 */
function validaAndUpdateCart(elem, divId, articulo,text){
	var value = stringToInt(articulo.cantidad);
	if(value > 0){
		$(elem).val(value);
		articulo.cantidad = value;
        updateCart(divId, articulo);
	} else {
		$(elem).val(text);
		articulo.cantidad = 0;
		updateCart(divId, articulo);
	}
}

function stringToInt(string){
	var value = jQuery.trim(string);
	value = value.replace(/[^0-9.]/g,"");
	if(value != ''){
		var intValue = Math.ceil(value);
		//Compruebo si es un valor numérico
		if (isNaN(intValue))
			return -1;
    	else
    		return intValue;
	} else{
		return -1;
	}
}

// Certificado de ragalos
function readyToUpdate(elem){
	if(elem.id == 'otroRadio'){
		swapMessage($("#otraCantidad"));
		$("#otraCantidad").focus();
		
	} else {
		$("#otraCantidad").val('Otro Monto');
	}
}

function focusOtraCantidad(elem){
	$('#otroRadio').click(); 
	swapMessage(elem);
}


function rolloverrow(tr){
    tr.className="highlight";
    $(tr).css("cursor","pointer");
    
    }
    
function rolloutrow(tr){
    tr.className="";
    $(tr).css("cursor","default");
    }
    
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function moveCart(e) {
        //var vleft =$("#certif").position().left+$("#certif").width();
        var vleft =$('#container').position().left+$('#container').width()-$('#shoppingCart').width()-13;

        newPos =  menuYloc+$(document).scrollTop()+10;
        //console.debug('newPos: '+newPos+' certTop: '+certTop+ ' registro: '+registro);
        if (newPos >= certTop && newPos <= registro){
        //console.debug('Mover a newpos:'+newPos );
                //var offset = newPos;
                $(name).animate({top:newPos+"px",left: vleft},{duration:500,queue:false});
                //$(name).css({top:newPos+"px",left: vleft});
        }else if (newPos > registro){
        //console.debug('Mover a registro:'+registro );
                //var offset = registro;
                $(name).animate({top:(registro-10)+"px",left: vleft},{duration:500,queue:false});
                //$(name).css({top:registro+"px",left: vleft});
        }else if(newPos < certTop){
                //var offset = certTop;
        //console.debug('Mover a certTop:'+certTop );
                $(name).animate({top:certTop+"px",left: vleft},{duration:500,queue:false});
                //$(name).css({top:certTop+"px",left: vleft});
        }
         /*   if (menuYloc >= certTop && menuYloc <= registro ){
                console.debug('menuY: '+menuYloc+' certTop: '+certTop+ ' registro: '+registro);
                var offset = parseInt(menuYloc)+$(document).scrollTop();
                $(name).animate({top:offset+"px"},{duration:500,queue:false});
            }*/ 
    }



function enviarBusqueda(){
	$("input#offset_SearchProduct").val(0);
	$("form#formSearchProduct").submit();
}

function todasCategorias(){
	$("input.categoryCheck").each(function(el){
		this.checked = true;
	});
}

function seleccionaMarca(p){
  $("input#path").val(p);
}

function setPage(offset){
	$("input#offset_SearchProduct").val(offset);
 	$("form#formSearchProduct").submit();
 	return false;
}

function setCategoria(path,id){
 	$("input.categoryCheck").each(function(el){
 	   if($(this).val()==id){this.checked= true;}else{this.checked= false;}
 	});
    $("input#deptos").val(id);
    $("input#offset_SearchProduct").val(0);
 	$("form#formSearchProduct").submit();
 	return false;
}
 	
function setElement(tipo){
 	$("#element_SearchProduct").val(tipo);
 	$("#multicatcount_SearchProduct").val("");
	if($("input.categoryCheck:checked").length == 0){
		$("input.categoryCheck:unchecked").each(function(el){
			this.checked= true;
	    });
	}
	$("form#formSearchProduct").submit();
}

function getTodayAndRange(){
	var today = new Date();
	var strToday = getFormatedDate(today);
	var range = strToday;
	return {today:strToday,range:range,date:today};
}

function fillCeros(number){
	if(number < 10)
		return '0'+number;
	else
		return ''+number;
}

function getFormatedDate(date){
	var strDate = fillCeros(date.getDate())+'/'+fillCeros(date.getMonth() + 1)+'/'+date.getFullYear(); 
	return strDate;
}

function showThickBoxWithZoom(ele,title,imgSrc,srcImgZoom){
	tb_show_zoom(title,imgSrc,false,srcImgZoom);
	//tb_show(title,imgSrc,false);
	$(ele).blur();
}

/**************** INIT *******************/

$(document).ready(function(){
    
    $('img#Image10, img#Image13').parent().click(function(){
        $('form#formSearchEvent').submit();
        return false;
    });
    
    var todayAndRange = getTodayAndRange();

    $('#datePickerHeader').DatePicker({
		flat: true,
		format:'d/m/Y',
		date: todayAndRange.range,
		current: todayAndRange.today,
		calendars: 1,
		mode: 'single',
		prev: '<img align="middle" src="'+baseSiteImg+'/mr/c_back.jpg" width="18" height="18" border="0" name="back" alt="back"/>',
		next: '<img align="middle" src="'+baseSiteImg+'/mr/c_next.jpg" width="18" height="18" border="0" name="next" alt="next"/>',
		starts: 1,
		onChange: function(formated, date){
    		$('#date').val(formated);
    		$('#startDate').val(formated);
		}
	});
    $("#MR3b").css("display","none");
    $("#MR3b").css("visibility","visible");
    
    $("a#orderTipo").showMenu({
        query: "#MR4"
    });
    
    $("a#orderFecha").showMenu({
        query: "#MR3b"
    });
    //close button
    $('img#Image2b').parent().click(function(){
        $('#MR3b').hide();
        return false;
    });
    
    //ok button
    $('img#Image9b').parent().click(function(){
    	sendParams('');
    	$("#MR3b").hide();
        return false;
    });
    
    $("#hoy").click(function(){
    	$('#datePickerHeader').DatePickerSetDate(todayAndRange.today, true);
    	$('#date').val(todayAndRange.today);
    	$('#startDate').val(todayAndRange.today);
    	sendParams('');
    });
	
    $("#mes").click(function(){
    	var currentDate = $('#datePickerHeader').DatePickerCurrentDate();
    	var endDate = currentDate.date;
    	endDate.setMonth(endDate.getMonth());
    	endDate.setDate(endDate.getMaxDays());
    	var strEndDate = getFormatedDate(endDate);
    	$('#date').val("Todo el mes");
    	$('#startDate').val(currentDate.formatedDate);
    	$('#endDate').val(strEndDate);
    	sendParams('');
    });
    
	$('#calendars').DatePicker({
		flat: true,
		format:'d/m/Y',
		date: todayAndRange.range,
		current: todayAndRange.today,
		calendars: 2,
		mode: 'range',
		prev: '<img align="middle" src="'+baseSiteImg+'/mr/c_back.jpg" width="18" height="18" border="0" name="back" alt="back"/>',
		next: '<img align="middle" src="'+baseSiteImg+'/mr/c_next.jpg" width="18" height="18" border="0" name="next" alt="next"/>',
		starts: 1,
		onChange: function(formated, date){
			var texto="";
			$('#startDate').val(formated[0]);
			texto=formated[0];
			if(formated[0] != formated[1]){
				$('#endDate').val(formated[1]);
				texto += " - "+ formated[1];
			}else{
				$('#endDate').val("");
			}
			$('img.ver_calendario').hide();
			$('label#datesSelected').text(texto);
		}
	});
	
	/*Implemtación del mouseover y mouseout para las flechas del calendario*/
	$(".datepickerGoPrev a").each(function(i,item){
		$(item).mouseover(function (){
			$(this).children("img").attr("src",baseSiteImg+'/mr/c_back_over.jpg');
		})  
		$(item).mouseout(function (){
			$(this).children("img").attr("src",baseSiteImg+'/mr/c_back.jpg');
		}) 
	});
	
	$(".datepickerGoNext a").each(function(i,item){
		$(item).mouseover(function (){
			$(this).children("img").attr("src",baseSiteImg+'/mr/c_next_over.jpg');
		})  
		$(item).mouseout(function (){
			$(this).children("img").attr("src",baseSiteImg+'/mr/c_next.jpg');
		}) 
	});


    

        $("input.priceText").each(function(){
            $(this).blur(function(e){
				var h=0;
                 if($("#lowpT").val()=="") $("#lowpT").val("0");
                var l=parseInt($("#lowp").val( currencyToNumber($("#lowpT").val()) ).val());
                if($("#highpT").val()==""){
                    h=parseInt($("div.myslider-range").slider('option', 'max'));
                    $("#highp").val("max");
                    $("#highpT").val(">"+new String(h).formatCurrency());
                }else
                    h=parseInt($("#highp").val( currencyToNumber($("#highpT").val()) ).val());
                if(l>h){
                    $("#lowp").val( $("#highp").val());
                    $("#lowpT").val( $("#highpT").val()); 
                }
                if(h<l){
                    $("#highp").val( $("#lowp").val());
                    $("#highpT").val( $("#lowpT").val());
                }
                $("div.myslider-range").slider('values',0,l);
                $("div.myslider-range").slider('values',1,h);
                //showRanges();
            });
        });
        $("form#formSearchProduct").submit(function(){
            var id="";
            $("input.categoryCheck:checked").each(function(el){
                id= (id=="")?$(this).val():id+","+$(this).val();
            });
            $("input#deptos").val(id);
            //validar si no checks sigue la validacion
            
            if($("input.categoryCheck").length>0 && id==""){
                alert("Seleccione al menos una categoría");
                return false;
            }else {
            	//Si se selecciono una sola categoría la lista de resultados
            	//no debe ser agrupada (multicatcount=-1)
            	if(id.split(",").length == 1){
            	    $("input#multicatcount_SearchProduct").val("-1");
            	}
            	return true;
            }
        });
        
      //** Validar numeros
      $("input.keyNumber").keypress(keyNumber);
	  
	  $('input[name=certificado]').click(function(e){
        $(this).next('label').fadeOut().fadeIn("slow");
	  });
	  
    $('.i_lista').parent().click(function(){
        imprimir('lista');
        return false;
    });
    $('.i_articulos').parent().click(function(){
        imprimir('filtro');
        return false;
    });
    
      if(($('#startDateR').val()=='' && $('#endDateR').val()=='') && $('#tipoEvento').val() == ''){
    	  $('div.busqueda2').hide();  
      }
      
	
    $('a#busqAvanzada').click(function(){
        $('div.busqueda2').toggle();
        return false;
    });
    $('img#Image14').parent().click(function(){
        $('div.busqueda2').hide();
        return false;
    });
    
    $('#verCal').click(function(e){
        $('div#MR3').css({top:e.pageY, left:e.pageX});
        $('div#MR3').show();
        return false;
    });
    $('img#Image2').parent().click(function(){
        $('div#MR3').hide();
        return false;
    });
    //Ok calendar header
    $('img#Image9').parent().click(function(){
        $('div#MR3').hide();
        return false;
    });
    
    $('div#MR3').hide();
    //necesario para calcular el tamaño del contenedor del calendario
    $('div#MR3').css("visibility","visible");
    
    //Que es plan celebra
    $('#Image75').parent().showMenu({
        query: "#MR5b"
    });
    //Close que es plan celebra
    $("#MR5b_Image2").parent().click(function(){
    	$("#MR5b").hide();
    	return false;
    });
    
    //Que es plan clásico
    $('#Image89').parent().showMenu({
        query: "#MR4b"
    });
    //Close que es plan clásico
    $("#MR4b_Image2").parent().click(function(){
    	$("#MR4b").hide();
    	return false;
    });
    
    //Info de compras Casa Palacio
    $('.prodCP').parent().showMenu({
        query: "#MR7b"
    });
    //Close Info de compras Casa Palacio
    $("#MR7b_Image2").parent().click(function(){
    	$("#MR7b").hide();
    	return false;
    });
    
       
});
