/********************************* GENERICOS
 */
 function fecha(fec)
{
    var mifecha;
    var mydate=(fec===undefined?new Date():fec);

    var year=mydate.getYear();
    if (year < 1000){
        year+=1900;
    }
    var day=mydate.getDay();
    var month=mydate.getMonth()+1;
    if (month<10){
        month="0"+month;
    }
    var daym=mydate.getDate();
    if (daym<10){
        daym="0"+daym;
    }
    mifecha=month+"/"+daym+"/"+year;
    
    return mifecha;
}
function stringUTCToDate(fec){
    if(fec===undefined) return new Date();
    var sep=fec.split(/[- :.\\\/]/);
    if(sep.length==3)
        return new Date(sep[0],sep[1],sep[2]);
    else if(sep.length>=6)
        return new Date(sep[0],sep[1],sep[2],sep[3],sep[4],sep[5]);
}
function currencyToNumber(val){
    if(val===undefined) return 0;
    return parseInt(val.split(/[$,>]/).join(""));
}


// Simulates PHP's date function
Date.prototype.format = function(format) {
    var returnStr = '';
    var replace = Date.replaceChars;
    for (var i = 0; i < format.length; i++) {
        var curChar = format.charAt(i);
        if (replace[curChar]) {
            returnStr += replace[curChar].call(this);
        } else {
            returnStr += curChar;
        }
    }
    return returnStr;
};
Date.replaceChars = {
    shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
    longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
    
    // Day
    d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
    D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
    j: function() { return this.getDate(); },
    l: function() { return Date.replaceChars.longDays[this.getDay()]; },
    N: function() { return this.getDay() + 1; },
    S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
    w: function() { return this.getDay(); },
    z: function() { return "Not Yet Supported"; },
    // Week
    W: function() { return "Not Yet Supported"; },
    // Month
    F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
    m: function() { return (this.getMonth() < 11 ? '0' : '') + (this.getMonth() + 1); },
    M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; },
    n: function() { return this.getMonth() + 1; },
    t: function() { return "Not Yet Supported"; },
    // Year
    L: function() { return "Not Yet Supported"; },
    o: function() { return "Not Supported"; },
    Y: function() { return this.getFullYear(); },
    y: function() { return ('' + this.getFullYear()).substr(2); },
    // Time
    a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
    A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
    B: function() { return "Not Yet Supported"; },
    g: function() { return this.getHours() % 12 || 12; },
    G: function() { return this.getHours(); },
    h: function() { return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12); },
    H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
    i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
    s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
    // Timezone
    e: function() { return "Not Yet Supported"; },
    I: function() { return "Not Supported"; },
    O: function() { return (this.getTimezoneOffset() < 0 ? '-' : '+') + (this.getTimezoneOffset() / 60 < 10 ? '0' : '') + (this.getTimezoneOffset() / 60) + '00'; },
    T: function() { return "Not Yet Supported"; },
    Z: function() { return this.getTimezoneOffset() * 60; },
    // Full Date/Time
    c: function() { return "Not Yet Supported"; },
    r: function() { return this.toString(); },
    U: function() { return this.getTime() / 1000; }
};
String.prototype.trim = function () {
        return this.replace(/^\s*/, "").replace(/\s*$/, "");
    }
String.prototype.formatCurrency=function() {
    var num=this;
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	   num = "0";
	var sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	var cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	   cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	   num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num +'.'+ cents);
}
    function isNumber(val) {
        return val=="\0" ||/^([\b\d]+)$/.test(val);
    }
    function isEditable(val){
        //return val=="\0" || /^[\b:"\*\+áéíóúÁÉÍÓÚ]+$/.test(val);
        return !/^([<>\?¿¡'¨~\/&\(\)"!\*;#\$%=´{}\[\]`]+)/.test(val);
    }
    function isAlpha(val){
        return /^[ \w]+$/.test(val);
    }
    function isDate(val){
        return /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/.test(val);

    }
    function isEmail(val){
    	return /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/.test(val);
    }
    /******************** FUNCIONES DE LA CAJA DE BUSQUEDA *****************
     */
    
    /*depurar codigo
    function goBack(path,delCat, catid){       
        var formSearch = document.getElementById("formSearch");
        formSearch.cat_desc.value = delCat;
        if(catid!=undefined && catid!='') 
            $('input#catid').val(catid);
        go(path);
    }*/
    function go(path, catDesc){
        if(document.getElementById("originalQuery")){
            $("input#query").val(document.getElementById("originalQuery").value);
        }
       if (path !== undefined) {
            setPath(path);
        }
        if (catDesc !== undefined) {            
            setCatDescription(catDesc);
        }else{
            setCatDescription("");
         }
        
        
        var formSearch=document.getElementById("formSearch");
        $("input#offset").val( 0);
        $("input#parent_cat").val("");
        formSearch.submit();
    }
    function setPath(path){
        //var formSearch=document.getElementById("formSearch");
        //formSearch.path.value=path;
        $("input#path").val(path);
    }
    function setCatDescription(catDesc){
        //var formSearch = document.getElementById("formSearch");
        if(catDesc != ""){
            if($("input#parent_cat").val()==""){
                //formSearch.cat_desc.value = catDesc;
                 $("input#cat_desc").val(catDesc);
            }else{
                //formSearch.cat_desc.value = formSearch.parent_cat.value+"|"+catDesc;
                $("input#cat_desc").val($("input#parent_cat").val()+"|"+catDesc);
            }
        }                   
    }
     /*depurar codigo
    function setParentCat(parentId){        
        var formSearch = document.getElementById("formSearch");
        formSearch.parent_cat.value = parentId;
        //alert(formSearch.parent_cat.value);
    }*/

    function keyQuery(e){
        var tecla=(document.all) ? e.keyCode : e.which;
        //console.log(tecla);
        if(tecla == 13) {            
            $("input#path").val("");
            return true;
        }else {
           var  strChar=String.fromCharCode(tecla);
            return isAlpha(strChar)||isEditable(strChar);            
        }
        
    }
    function keyNumber(e){
       var  tecla=(document.all) ? e.keyCode : e.which;
        //console.log(tecla);
            return isNumber(String.fromCharCode(tecla));
    }
     /*depurar codigo
    function sendQuery(){
        if (document.getElementById("cmbCategorias").selectedIndex>0){
            go(document.getElementById("path").value);
	    }else{
	        go("");
	    }
    }*/
    /*depurar codigo
    function goPage(path){
        if(document.getElementById("originalQuery")){
            $("input#query").val(document.getElementById("originalQuery").value);
        }
        
        setPath(path);
        $("#formSearch").submit();
        $("#formSearchEvent").submit();
    }*/
    /*depurar codigo
    function goMenu(path,id){
        $('input#originalQuery').val('');
        $('input#query').val('');
        $('input#catid').val(id);
        go(path);
    }*/
     /*depurar codigo
   function setOrden(value,ioffset,ihits){
      document.getElementById("sort_by").value =value;
      document.getElementById("offset").value = ioffset;
      document.getElementById("hits").value  = ihits;
        goPage(document.getElementById("path").value);
    }
    */
    /*depurar codigo
    function setHits(hitsh){
        $("input#hits").val(hitsh);
        go();
    }*/
     /*depurar codigo
    function setOffset(ioffset){
        document.getElementById("offset").value=ioffset;
        goPage(document.getElementById("path").value);
    }*/
     /*depurar codigo
   function setVista(elem){
        $("input#element").val(elem.value);
        go();
    }
    */
    /********************** FUNCIONES DE COMPARACION **********************
     */
    
function verifyThree(chkbox){
    if(chkbox.checked){
        var total = total + 1;
        if(total > 3){
            chkbox.checked=false;
            alert("Solo se pueden seleccionar 3 para comparar");
            total = total - 1;
        }else{
            buscar = buscar + " " + chkbox.value;
            if(buscar1==""){
                buscar1 = chkbox.value;
            }else{
                if(buscar2 ==""){
                    buscar2 = chkbox.value;
                }else{
                    buscar3 = chkbox.value;
                }
            }
        }
    }else{
        if(buscar1 == chkbox.value){
            total = total - 1;
            buscar1 = "";
        }
        if(buscar2 == chkbox.value){
            total = total - 1;
            buscar2 = "";
        }
        if(buscar3 == chkbox.value){
            total = total - 1;
            buscar3 = "";
        }
    }
    total = 0;
    if(buscar1==""){total = total + 0;}else{total = total + 1;}
    if(buscar2==""){total = total + 0;}else{total = total + 1;}
    if(buscar3==""){total = total + 0;}else{total = total + 1;}
    
}
/***********autocomplete**************************/

function findValue(li) {
    if( li == null ) return alert("No match!");
    if( !!li.extra )
    {
        var sValue = li.extra[0]; 
    }else{ 
        var sValue = li.selectValue;
    }
}
function formatItem(row) {
    return row[0]+(row[0]!=""&&row[1]!=""?", ":"")+row[1];
}

function quitaAcentos( texto){
	var consignos = "áàäéèëíìïóòöúùuÁÀÄÉÈËÍÌÏÓÒÖÚÙÜçÇñÑ";
	var sinsignos = "aaaeeeiiiooouuuAAAEEEIIIOOOUUUcCnN"; 
	var data = texto;
	var returnText = "";
	for (var i = 0; i < data.length; i++) {
		var index = consignos.indexOf(data.charAt(i));
		if(index > -1){
			returnText+=(sinsignos.charAt(index));
		} else {
			returnText+=(data.charAt(i));
		}
	}
	return returnText;
}
function inputNumber(elems){
    $(elems).each(function(){
            //** Validar numeros
            $(this).keypress(keyNumber);
            //** Preparar el numero para la captura
            $(this).focus(function(e){
               // if($(this).val()!="" && isNumber($(this).val())) 
                    $(this).val(currencyToNumber($(this).val()));
                // else
                 //   $(this).val('0');
            });
            //** formatear el texto y asignar el numerico a los priceValue
            $(this).blur(function(e){
                if($(this).val()!="" && $(this).val().indexOf("$")==-1) $(this).val($(this).val().formatCurrency());
            });
    });
}
/*********************** UTILERIAS ****************/

/********************* DETALLE DEL PRODUCTO ****************/
//Manejo de las vistas alternativas de un producto
function clearAndPutImage(idContainer,srcImg,altText,srcZoomImg){
	 var img = new Image();
	 $(img).attr("src", srcImg)
	 	   .attr("alt", altText)
	 	   .attr("width", 334)
	 	   .attr("height", 417);
	var container = $("#"+idContainer).empty();
	container.append(img);
	
	if(srcZoomImg != null && jQuery.trim(srcZoomImg) != ""){
		var link = $(document.createElement("a"));
		link.append("Zoom Image");
		link.addClass("zoom");
		container.append(link);
		link.click(function(){
			container.zoom({image:srcZoomImg}); 		
			return false;
		});
	}
}
//Manejo de combos 
/*
	Reutiliza la funcion borrar() y agregar()
	En ella se maneja una variable global llamada contador
	que guarda el número de productos
*/

function borrarProducto(numItem){
	var contadorTemp = contador-1;
	if(numItem >0) {
		if(numItem < contadorTemp){
			for(var i=numItem;i<contadorTemp;i++){
				copyOptionsAndRemove(i,"cantidad");
				copyOptionsAndRemove(i,"colores");
				copyOptionsAndRemove(i,"talla1");
				copyOptionsAndRemove(i,"talla2");
			}
		}
		borrar();
		$("#div_cantidad_"+contador).hide();
	}
}

function agregarProducto(){
	var valorPrevioContador = contador;
	agregar();
	if(contador>valorPrevioContador){
		$("#div_cantidad_"+valorPrevioContador).show();
	}
}

function copyOptionsAndRemove(numRenglon,nombre){
	var aSelect = $("#div_cantidad_"+(numRenglon)+" select[name='"+nombre+"']");
	var deSelect = $("#div_cantidad_"+(numRenglon+1)+" select[name='"+nombre+"']");
	aSelect.children().remove();
	var index = deSelect[0].selectedIndex;
	aSelect.append(deSelect.children().clone());
	aSelect[0].selectedIndex = index;
	//limpia el campo seleccionado
	deSelect[0].selectedIndex=0;
}

/*********************** INITS ****************/
$(function(){    
    
    $("input.inputbuscador").each(function(i){
        $(this).keypress(keyQuery);    
    });
    
    inputNumber("input.priceText");
    
    $("input#query").each(function(i){
        $(this).keypress(keyQuery);    
    });
    $("form#formSearch").submit(function(){
        $('input#path').val('');
        $('input#offset').val('0');
        $('input#sort_by').val('');
        $('input#originalQuery').val($('input#query').val());
        return $('input#query').val().trim()!='';       
    });
    
    $('li.opinion a').click(function(){
        window.open($(this).attr('href'),'_blank','width=284,height=258');
        return false;
    });
    $('ul.fmenu li.title ul li a').click(function(){
        var target=$(this).attr('target');
         console.log(target);
        if(target){
            if(target.indexOf('popup')==0){
                 window.open($(this).attr('href'),target.split(',')[0],'width='+target.split(',')[1]+',height='+target.split(',')[2]);
            }else{
                  window.open($(this).attr('href'),target);
            }
        }else{
              window.open($(this).attr('href'),'_self');
        }
        
        return false;
    });
    $('a.didumean').click(function(){
        $('input#query').val($(this).text());
        $('form#formSearch').submit();
        return false;
    });
    //Si no tiene alguna recomendación, oculta el div "completa tu compra"
    $('div.related:not(":has(div.item)")').hide();
    
    // windows dialog de la promoción
    $('#promocionDialog').palacioPopup({itemWidth:220,listStyle:'disc'});
   
});