/* Variables requeridas
 * BASE URL = $view->getBaseUrl();
 * UpdateTwitter = $view->linkTo('AjaxRss/updateTwitter')
 * UpdateFaceBook = $view->linkTo('AjaxRss/updateFacebook')
 */
$(document).ready(function(){
    initZoom();
    centerMiniImages();
    centerImagesCatalogs();
    $('.btn').button();
    initSelectGruposTags();
    initSelectCatalogos();
    initCustomSearch();
    initKindViewCatalog(0);
    initClickTagsSearch();
    initLinkMoreTags();
    initLinkNavigation();
    fixLongNamesVerticalMenu('menuVertical',40);
    fixLongNamesVerticalMenu('submenuVertical',20);
    $('#formCitas').validate({
        errorPlacement: function(error, element) {
            //error.appendTo($('#load'));
            $('#load').html(error);
        },
        rules: {
            telefono: {
                minlength: 10
            }
        },
        messages: {
            nombre:{
                required:""
            },
            mail: {
                required:"",
                email:"E-mail inv&aacute;lido"
            },
            telefono:{
                required:"",
                digits:"Ingresa solo n&uacute;meros",
                minlength:"El n&uacute;mero debe ser a 10 d&iacute;gitos"
            },
            comentario:{
                required:""
            }
        }/*,
            debug:true*/
    });
    iniCaptify();
    var galeria = $('#galeria').val();
    
    if(galeria != 0)
    {
        var tipo=$('#typeGallery').val();
        if(tipo != undefined)
        {
            if(tipo=='galeriauno')
            {
                gallery();
            }
            else
            {
                if($('#thumbs').find('li').length > 0)
                gallery2();
            }
        }
    }
    
    var edicion = false;
    inicializa_mapas(edicion);

    $('.datepicker').each(function(){
        var id = $(this).attr('id');
        if(id != 'citas_datepicker')
        {
            $(this).datepicker({
                dateFormat: 'yy-mm-dd',
                monthNames: ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'],
                dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa']
            });
        }
        else
        {
            $(this).datepicker({
                dateFormat: 'yy-mm-dd',
                minDate: +0,
                monthNames: ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'],
                dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'],
                onSelect:function(fecha)
                {
                    $('#fecha_cita').val(fecha);
                    arrFecha = fecha.split('-');
                    year = arrFecha[0];
                    day = arrFecha[2];
                    month = parseInt(arrFecha[1], 10)-1;
                    $('#calendar').fullCalendar('gotoDate', year , month, day);
                }
            });
        }
    });

    // inicializar calendario
    initCalendar();
       
    $("#form_mensajes").validate({
        messages: {
            nombre:{
                required:"Por favor escriba su nombre..."
            },
            correo: {
                required:"Por favor escriba su email...",
                email:"El email no es v&aacute;lido..."
            },
            contenido:{
                required:"Por favor escriba su mensaje..."
            }
        },
        errorContainer: "#msgError",
        errorLabelContainer: "#msgError"
    });
//    getGroupTags();
    hideMenuCatalogosVistaElemento();
});



function hideMenuCatalogosVistaElemento()
{
    var vistaElemento = $('#vistaElemento').val();
    if(vistaElemento == undefined)  vistaElemento = 0;
    else                            vistaElemento = parseInt(vistaElemento);

    if(vistaElemento == 1)
    {
        $('#botonesCatalogosTienda').hide();
    }
}

function iniCaptify()
{
    $('img.captify').captify();
}

function muestraForm()
{
    $('#area_citas').show('slow');
    $('#txtAction').html('<a onclick="escondeForm()">Cerrar</a>');
}

function escondeForm()
{
    $('#area_citas').hide();
    $('#txtAction').html('<a onclick="muestraForm()">Solicita aqui tu cita</a>');
}

function solicitud()
{
    if($('#formCitas').valid())
    {
        var date = new Date();        

        var id_sitio = $('#idSitio').val();
        var id_usuario = $('#idUsuario').val();
        var nombre = $('#nombre').val();
        var correo = $('#mail').val();
        var telefono = $('#telefono').val();

        var hora_inicio = $('#hora').val()+':'+$('#min').val();
        var arrHora = $('#duracion').val().split(':');
        var mins = parseFloat($('#min').val()) + parseFloat(arrHora[1]);
        var hrs = parseFloat($('#hora').val()) + parseFloat(arrHora[0]);
        if(mins >= 60)
        {
            var exc = mins - 60;
            hrs += 1;
            if(exc == 0)
                mins = '00';
            else
                mins = exc;
        }
        var hora_fin = hrs+':'+mins;

        var comentario = $('#comentario').val();
        var fecha_cita = $('#fecha_cita').val();
        var mes = date.getMonth()+1;
        if(mes < 10)
            mes = '0'+mes;
        var fecha = date.getFullYear()+'-'+mes+'-'+date.getDate()+' '+date.getHours()+':'+date.getMinutes();

        permitido = true;        
        if(fecha_cita == date.getFullYear()+'-'+mes+'-'+date.getDate())
            if($('#hora').val() < date.getHours())
                permitido = false;
        
        if(permitido)
        {
            loading('<span style="font-size:12px;">Realizando solicitud</span>');
            $.post(linkDisponible,{
                id_sitio:id_sitio,
                hora_inicio:hora_inicio,
                hora_fin:hora_fin,
                fecha_cita:fecha_cita
            },function(data){
                if(data == 0)
                    insertaCita();
                else
                {
                    alert('Horario ocupado');
                    endLoading();
                }
            });
        }
        else
            alert('Por favor revisa la hora de tu solicitud.');
    }
}

function insertaCita()
{
    var date = new Date();
    var id_sitio = $('#idSitio').val();
    var id_usuario = $('#idUsuario').val();
    var nombre = $('#nombre').val();
    var correo = $('#mail').val();
    var telefono = $('#telefono').val();

    var hora_inicio = $('#hora').val()+':'+$('#min').val();
   
    var arrHora = $('#duracion').val().split(':');
    var mins = parseFloat($('#min').val()) + parseFloat(arrHora[1]);
    var hrs = parseFloat($('#hora').val()) + parseFloat(arrHora[0]);
    if(mins >= 60)
    {
        var exc = mins - 60;
        hrs += 1;
        if(exc == 0)
            mins = '00';
        else
            mins = exc;
    }
    var hora_fin = hrs+':'+mins;

    var comentario = $('#comentario').val();
    var fecha_cita = $('#fecha_cita').val();
    var fecha = date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate()+' '+date.getHours()+':'+date.getMinutes();
    var mail_destino = $('#mail_destino') .val();
    var recaptcha_challenge_field = $('#recaptcha_challenge_field').val();
    var recaptcha_response_field = $('#recaptcha_response_field').val();
    
    $.post(linkInsertaCita,{
        recaptcha_challenge_field:recaptcha_challenge_field,
        recaptcha_response_field:recaptcha_response_field,
        mail_destino:mail_destino,
        id_sitio:id_sitio,
        id_usuario:id_usuario,
        nombre:nombre,
        correo:correo,
        telefono:telefono,
        hora_inicio:hora_inicio,
        hora_fin:hora_fin,
        comentario:comentario,
        fecha_creacion:fecha,
        fecha_cita:fecha_cita
    },function(data)

    {
            if(data == 1)
            {
                //endLoading();
                $('#load').html('<div class="cita_success">Tu solicitud ha sido registrada.</div></hr>');
                $('#recaptcha_response_field').val('');
                escondeForm();
            }
            if(data == 2)
            {
                //endLoading();
                $('#load').html('<div class="cita_error">Se ha introducido las palabras incorrectamente, intenta de nuevo.</div>');
            }
            if(data == 0)
            {
                //endLoading();
                $('#load').html('<div class="cita_error">Se ha producido un error al generar la cita, por favor intenta mas tarde.</div>');
            }
        });
}

function refreshTwitter(name)
{    
    $('#'+name+'twOverFlow').html('<div style="text-align:center"><img src="'+baseUrl+'/images/silver-blue/images/loading.gif" style="margin-top:10em;"/></div>');
    $.post(UpdateTwitter,{
        name:name,
        width:width
    },function(data){
        $('.rss_'+name).each(function(){
            $(this).html(data);
        });
    });
}

function refreshFacebook(id)
{
    $('#'+id+'twOverFlow').html('<div style="text-align:center"><img src="'+baseUrl+'/images/silver-blue/images/loading.gif" style="margin-top:10em;"/></div>');
    $.post(UpdateFaceBook,{
        id:id,
        width:width
    },function(data){
        $('#rss_'+id).html(data);
    });

}

function gallery()
{
//    ancho = width.split('p');
    var ancho = $('#photos').width();
    //'colorFondo':fondoElement
    var fondoElement=$('#fondoElement').val();
//    alert(ancho);
    $('.galleryview').galleryView({
        panel_width: ancho - 5,
        panel_height: 300,
        frame_width: 100,
        frame_height: 100,
        overlay_height: 40,
        overlay_position: 'bottom',
        overlay_opacity: 0.4,
        overlay_color: fondoElement,
        nav_theme: 'light',
        background_color:fondoElement
    });
    $('.panel').each(function(){
        $(this).css('background', fondoElement);
    });
}

function initCalendar()
{
    var date = new Date();
    var options = {
        aspectRatio: 1,
        defaultEventMinutes:60,
        slotMinutes : 15,
        columnFormat:{
            month: 'ddd',    // Mon
            week: 'ddd d', // Mon 9/7
            day: 'd MMMM '  // Monday 9/7
        },
        /*loading: function(bool) {
            if (bool) $('#loading').show();
            else $('#loading').hide();
        },*/
        // eventsources requiere la url de donde llega el archivo json
        eventSources:[$('#linkGetCalendar').attr('value')],/// pruebaGetPost
        theme:true,
        defaultView :'agendaDay',
        //inicializa fecha de vista
        year:date.getFullYear(),
        month:date.getMonth(),
        date:date.getDate(),
        monthNames:['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
        monthNamesShort:['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio','Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],

        dayNames:['Domingo', 'Lunes', 'Martes', 'Miercoles','Jueves', 'Viernes', 'Sabado'],
        dayNamesShort:['Dom', 'Lun', 'Mar', 'Mier', 'Jue', 'Vier', 'Sab'],
        buttonText:{
            today:    'Hoy',
            month:    'Mes',
            week:     'Semana',
            day:      'Día'
        },
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },
        editable: true,
        titleFormat:{
            month: 'MMMM yyyy',                             // September 2009
            week: "MMM d[ yyyy]{ '&#8212;'[ MMM] d ' de' yyyy}", // Sep 7 - 13 2009
            day: "dddd d 'de' MMM 'de' yyyy"
        },
        allDayText:'',
        minTime:$('#hora_inicio').val(),
        maxTime:$('#hora_final').val()
    }

    $('#calendar').fullCalendar(options);
}

function loading(texto)
{
    $('#load').html('<img src="'+baseUrl+'/images/ui/loading.gif" /><br/><span style="font-size:12px;">'+texto+'</span>');
}

function endLoading()
{
    $('#load').html('');
}

function mensajes()
{
    if($('#form_mensajes').valid())
    {
        var nom_fix = $('#nomFix').val();
        var id_usuario = $('#idUsuario').val();
        var nombre = $('#nombre').val();
        var correo = $('#correo').val();
        var contenido = $('#contenido').val();

        loading('<b>Enviando ...</b>');
        var recaptcha_challenge_field = $('#recaptcha_challenge_field').val();
        var recaptcha_response_field = $('#recaptcha_response_field').val();

        $.post(linkMensajesCaptcha,{
            recaptcha_challenge_field:recaptcha_challenge_field,
            recaptcha_response_field:recaptcha_response_field
        },function(respuesta){
           
            if(respuesta == 1)
                $.post(linkMensajes,{
                    id_usuario:id_usuario,
                    nom_fix:nom_fix,
                    nombre:nombre,
                    correo:correo,
                    contenido:contenido
                },function(data){
                    $('#area_mensajes').html(data);
                });
            else
                $('#load').html('<div class="error"><label class="error">Revisa las palabras de seguridad</label></div>');
        });
    }
}

/*
 * Inicializa el select para ejecutar consultas del grupo de tags seleccionados
 * Desplegara los productos correspondientes a los tags asociados al producto
 */
function initSelectGruposTags()
{
    var  url, idSitio,idGrupo;
    url = $('#urlGetProductsByTagGroup').val();
    idSitio = $('#idSitioTienda').val();
    
    $('#selectTagGroups').change(function(){
        $('#selectCatalogos').val('');//strSearchProduct
        $('#strSearchProduct').val('');
        idGrupo = $(this).val();
        if(idGrupo != '')
        {
            $.post(url,{
                'idSitio':idSitio,
                'idGrupo':idGrupo
            },function(data){
                $('#productsStoreData').html(data);
                $('.btn').button();
                initZoom();
            });
            
        }
    });
}

function initClickTagsSearch()
{
    $('.tagTienda').click(function(){
        var idTag,url;
        idTag = $(this).attr('id');
        idTag = idTag.split('-');
        idTag = idTag[1];

        if(idTag != undefined && idTag !='')
        {
            url = $('#urlGetProductsByTag').val();
            $.post(url,{
                'idTag':idTag,
                'edicion':0
            },function(data){
                $('#productsStoreData').html(data);
                $('.btn').button();
                initZoom();
                getGroupTags();
            //                add_to_cart();
            //                initKindViewCatalog(idCatalogo);
            });
        }
    });
    
}

function initLinkMoreTags()
{
    $('.linkMoreTags').click(function(){
        var idGrupoTags,url;
        idGrupoTags = $(this).attr('id');
        idGrupoTags = idGrupoTags.split('-');
        idGrupoTags = idGrupoTags[1];

        if(idGrupoTags != undefined && idGrupoTags !='')
        {
            url = $('#urlShowTagsGroup').val();
            $.post(url,{
                'idGrupoTags':idGrupoTags,
                'edicion':0
            },function(data){
                $('#divLinkMoreTags').html(data);
                initClickTagsSearch();
                $('#divLinkMoreTags').dialog({
                    resizable:false
                });
            //                add_to_cart();
            //                initKindViewCatalog(idCatalogo);
            });
        }
    });
}

/*
 * Inicializa el select para ejecutar consultas de catalogo seleccionado 
 */
function initSelectCatalogos()
{
    var  url, idSitio,idCatalogo,tipoVista,text;
    url = $('#urlGetProductsCatalog').val();
    idSitio = $('#idSitioTienda').val();
    tipoVista = $('#tipoVistaCatalogo').val();
    $('.catalogoSidebar').click(function(){

        var vistaPreview = $('#tipoPreview').val();
        if(vistaPreview == undefined)
        {
            vistaPreview = 0;
        }
        else
        {
            vistaPreview = 1;
        }

        //        $(this).addClass('ui-state-active');
        $('#selectTagGroups').val('');//strSearchProduct
        $('#strSearchProduct').val('');
        idCatalogo = $(this).attr('id');
        idCatalogo = idCatalogo.split('-');
        idCatalogo = idCatalogo[1];
        //        alert(idCatalogo);
        if(idCatalogo != '')
        {
            $.post(url,{
                'idSitio':idSitio,
                'idCatalogo':idCatalogo,
                'tipoVista':tipoVista,
                'esPreview':vistaPreview
            },function(data){
                $('#productsStoreData').html(data);
                $('.btn').button();
                initZoom();
                initKindViewCatalog(idCatalogo);
                getGroupTags();
            });
        }
        text = $(this).children('span').text();
        refreshLinkNavigation(text,idCatalogo);
    });
}

function refreshLinkNavigation(text,idCatalogo)
{
    //catalogoSidebar

    $('.navCat').html(text);
    $('.navCat').attr('id','cat-'+idCatalogo);
}

function initLinkNavigation()
{
    var  url, idSitio,idCatalogo,tipoVista;
    url = $('#urlGetProductsCatalog').val();
    idSitio = $('#idSitioTienda').val();
    tipoVista = $('#tipoVistaCatalogo').val();
    
    $('.navCat').click(function(){
        url = $('#urlGetProductsCatalog').val();        
        idSitio = $('#idSitioTienda').val();
        tipoVista = $('#tipoVistaCatalogo').val();
        
        //        $(this).addClass('ui-state-active');
        
        idCatalogo = $(this).attr('id');
        idCatalogo = idCatalogo.split('-');
        idCatalogo = idCatalogo[1];
        //        alert(idCatalogo);
        if(idCatalogo != '')
        {
            $.post(url,{
                'idSitio':idSitio,
                'idCatalogo':idCatalogo,
                'tipoVista':tipoVista
            },function(data){
                $('#productsStoreData').html(data);
                $('.btn').button();
                initZoom();
                initKindViewCatalog(idCatalogo);
                getGroupTags();
            });
        }
       
    });
}

/**
* trae los grupos de tags relacionados con el producto o productos q actualmente se estan viendo
*
*/
function getGroupTags()
{
    var strProducId = '';
    var id,url;
    $('.key').each(function(){
        id = $(this).attr('id');
        id = id.split('-');
        id = id[1];
        if(strProducId.length > 0)
        {
            strProducId +=',';
        }
        strProducId +=id;
    });
    if(strProducId.length > 0)
    {
        url = $('#urlGetGroupTagsCustom').val();
        $.post(url,{
            'strProducId':strProducId
        },function(data){
            $('#tagsGroupsData').html(data);
            initClickTagsSearch();
            initLinkMoreTags();
        });
    //alert(strProducId);

    }
}

/*
 * Ejecuta una busqueda tipo Like por tags de los productos existentes en la tienda
 */
function initCustomSearch()
{
    //inicializacion del click boton buscar
    $('#btnStrSearchProduct').click(function(){
        $('#selectTagGroups').val('');//strSearchProduct
        $('#selectCatalogos').val('');
        var url,strSearch,idSitio;
        idSitio = $('#idSitioTienda').val();
        strSearch = $('#strSearchProduct').val();
        url = $('#urlCustomSearch').val();
        
        $.post(url,{
            'idSitio':idSitio,
            'strSearch':strSearch
        },function(data){
            $('#productsStoreData').html(data);
            $('.btn').button();
            initZoom();
            getGroupTags();
        });
    });

    initAutocompleteCustomSearch();
//inicializacion del autocomplete
    
}

function initAutocompleteCustomSearch()
{
    var url;
    url = $('#urlTagsAutoComplete').val();
    var idSitioTienda = $('#idSitioTienda').val();
    $( "#strSearchProduct" ).autocomplete({
        source: function(request,response){
            var inputStr,index;
            inputStr = request.term;
            index = inputStr.lastIndexOf(',');
            if(index >= 0)
            {
                inputStr = inputStr.substring(index+1);
            }
            $.post(url,{
                'term':inputStr,
                'idSitio':idSitioTienda
            },function(data){
                response(data);
                $('.btn').button();
            },'json');
        },
        minLength: 2,
        select: function( event, ui ) {
            var oldStr,idx;
            oldStr = $('#strSearchProduct').val();
            idx = oldStr.lastIndexOf(',');
            if(idx >= 0)
            {
                oldStr = oldStr.substring(0,idx) + ',';
            }
            else{
                oldStr = '';
            }
            ui.item.value = oldStr + ui.item.value;
        },
        focus: function(event, ui) {
            return false;

        }

    });

}


function itemSelectedFromCatalog(idElement, idProduct, urlBase)
{
    var dir = urlBase+$('#nomFixPage').val()+'/Element/'+idElement+'/'+idProduct;
    location.href = dir;
}


/**
 * Cambia el contenido HTML entre 2 elementos
 * en este caso se trata unicamente de imagenes
 */
function changeImg(tagIdImg, tagIdImgPrincipal)
{
    var TDimgInferiorShow = $('#'+tagIdImg);
    var TDimgInferiorHide = $('#'+tagIdImg+'_hide');

    var TDimgPrincipalShow = $('#'+tagIdImgPrincipal+'_show');
    var TDimgPrincipalHideThumb = $('#'+tagIdImgPrincipal);
    var TDimgPrincipalHideReal  = $('#'+tagIdImgPrincipal+'_real');
    ////////////////////////////////////////////////////////////////////////////

    var HTMLimgInferiorShow = TDimgInferiorShow.html();
    var HTMLimgInferiorHide = TDimgInferiorHide.html();

    var HTMLimgPrincipalHideThumb = TDimgPrincipalHideThumb.html();
    var HTMLimgPrincipalHideReal  = TDimgPrincipalHideReal.html();
    ////////////////////////////////////////////////////////////////////////////

    TDimgPrincipalShow.html(HTMLimgInferiorHide);
    TDimgPrincipalHideThumb.html(HTMLimgInferiorShow);
    TDimgPrincipalHideReal.html(HTMLimgInferiorHide);

    TDimgInferiorShow.html(''+HTMLimgPrincipalHideThumb+'');   //Se centra la imagen miniatura. Evitando conflictos con la imagen con zoom
    TDimgInferiorHide.html(HTMLimgPrincipalHideReal);

    changeImageZoom(tagIdImgPrincipal+'_show', tagIdImgPrincipal+'_real');
    centerMiniImages();
}


function initZoom()
{
    var div;
    var imagen;
    var margen = 0;
    var HeightImg = 0;
    var WidthImg = 0;
    var proporcion = 0;
    var HeightTotal = 250;
    var WidthTotal = 250;

    $('.imagenPrincipal').each(function()
    {
        var div =  jQuery(this);
        var imagen = div.children();

        WidthImg = imagen.css("width");
        HeightImg = imagen.css("height");

        //Quitando los valores de px
        WidthImg = WidthImg.substr(0, WidthImg.length-2);
        HeightImg = HeightImg.substr(0, HeightImg.length-2);

        //En caso de que sea ceros los altos y/o anchos de la imagen o este en caracteristica auto'
        if(WidthImg <= 0 || HeightImg <= 0 || WidthImg == 'au' || HeightImg == 'au')
        {
            WidthImg = 100;
            HeightImg = 100;
        }

        proporcion = getProporcion(WidthTotal, HeightTotal, WidthImg, HeightImg);
        WidthImg  = fitSizeToTD(WidthImg,  proporcion);
        HeightImg = fitSizeToTD(HeightImg, proporcion);

        margen = parseInt((HeightTotal - HeightImg) / 2);

        $(this).miniZoomPan({
            sW: WidthImg,
            sH: HeightImg,
            lW: WidthImg * 2,
            lH: HeightImg * 2,
            margenTop: margen
        });
    });

    initSize();
}


function centerImagesCatalogs()
{
    var div;
    var imagen;
    var margen = 0;
    var HeightImg = 0;
    var HeightTotal = 112;
    var tamsEstilo = 10 + 2;

    $('.imagenCatalogo').each(function()
    {
        div =  jQuery(this);
        imagen = div.children();

        HeightTotal = getHeightFrom(div);
        HeightImg = getHeightFrom(imagen);

        margen = parseInt(HeightImg) + parseInt(tamsEstilo);
        margen = parseInt(HeightTotal) - parseInt(margen);
        margen = parseInt(margen / 2);

        imagen.css({
            marginTop : margen
        });
    });
}


function changeImageZoom(idImageShow, idImageSize)
{
    var margen = 0;
    var HeightImg = 0;
    var WidthImg = 0;
    var proporcion = 0;
    var HeightTotal = 250;
    var WidthTotal = 250;

    WidthImg = $('#'+idImageSize).width();
    HeightImg = $('#'+idImageSize).height();

    proporcion = getProporcion(WidthTotal, HeightTotal, WidthImg, HeightImg);
    WidthImg  = fitSizeToTD(WidthImg,  proporcion);
    HeightImg = fitSizeToTD(HeightImg, proporcion);

    margen = parseInt((HeightTotal - HeightImg) / 2);

    $('#'+idImageShow).swapInitImage({
        sW: WidthImg,
        sH: HeightImg,
        lW: WidthImg * 2,
        lH: HeightImg * 2,
        margenTop: margen
    });
}

function centerMiniImages()
{
    var div;
    var margen;
    var imagen;
    var HeightTotal = 0;
    var WidthTotal = 0;
    var tamsEstilo = 10 + 2;

    $('.minimg').each(function()
    {
        div =  jQuery(this);
        imagen = div.children();

        WidthTotal = getWidthFrom(div);
        HeightTotal = getHeightFrom(div);
       
        WidthImg = getWidthFrom(imagen);
        HeightImg = getHeightFrom(imagen);

        margen = parseInt(HeightImg) + parseInt(tamsEstilo);
        margen = parseInt(HeightTotal) - parseInt(margen);
        margen = parseInt(margen / 2);
        
        //alert(margen);
        //imagen.css({paddingTop: margen});
        imagen.css({
            marginTop : margen
        });
        centerOnlyAMiniImages(this.id);
    });
}


function getWidthFrom(objeto)
{
    var Width = 0;
    var Object2;

    Width = objeto.css("width");
    Width = Width.substr(0, Width.length-2);        //Quitando los valores de px

    if(Width <= 0 || Width == 'au')                 //En caso de que sea ceros o haya sido "auto""
    {
        Object2 = objeto.children();            //Pudo haber sido que es un nodo vacio u otro tag intermedio

        Width = Object2.css("width");
        if(Width == undefined)
        {
            Width = 100;
        }
        else
        {
            Width = Width.substr(0, Width.length-2);

            if(Width <= 0 || Width == 'au')                 //En caso de que sea ceros o haya sido "auto""
            {
                Width = 100;
            }
        }
    }

    return Width;
}


function getHeightFrom(objeto)
{
    var Height = 0;
    var Object2;

    Height = objeto.css("height");
    Height = Height.substr(0, Height.length-2);        //Quitando los valores de px

    if(Height <= 0 || Height == 'au')                 //En caso de que sea ceros o haya sido "auto""
    {
        Object2 = objeto.children();

        Height = Object2.css("height");
        if(Height == undefined)
        {
            Height = 100;
        }
        else
        {
            Height = Height.substr(0, Height.length-2);

            if(Height <= 0 || Height == 'au')                 //En caso de que sea ceros o haya sido "auto""
            {
                Height = 100;
            }
        }
    }

    return Height;
}


function centerOnlyAMiniImages(divId)
{
    var img;
    var HeightImg = 0;
    var WidthImg = 0;
    var HeightTotal = 0;
    var WidthTotal = 0;
    var difX = 0;
    var difY = 0;
    var tamsEstilo = 10 + 2;

    img = $('#'+divId+' img');
    WidthTotal = getWidthFrom($('#'+divId));
    HeightTotal = getHeightFrom($('#'+divId));

    WidthImg = getWidthFrom(img);
    HeightImg = getHeightFrom(img);

    difX = parseInt((parseInt(WidthTotal) - parseInt(WidthImg)) / 2);
    difX = parseInt(parseInt(difX) - parseInt(tamsEstilo/2));

    difY = parseInt((parseInt(HeightTotal) - parseInt(HeightImg)) / 2);
    difY = parseInt(parseInt(difY) - parseInt(tamsEstilo/2));

    if(difX < 0 || difY < 0)
    {
        img.css({
            left: difX
        });
        img.css({
            top: difY
        });
        img.css({
            position: 'relative'
        });
    }
    else
    {
        img.css({
            position: ''
        });
    }
}

function getProporcion(WidthTD, HeightTD, WidthImg, HeightImg)
{
    var proporcion = 0;
    //Si la imagen cabe en el TD
    if( (WidthImg <= WidthTD) && (HeightImg <= HeightTD) )
    {
        //Las medidas que debe de tomar serian
        //WidthImg, HeightImg
        proporcion = 1;
    }
    else
    {
        var  proporcionX = (WidthImg / WidthTD);
        var  proporcionY = (HeightImg / HeightTD);

        if(proporcionX > proporcionY)
        {
            proporcion = proporcionX;
        }
        else
        {
            proporcion = proporcionY;
        }
    }

    return proporcion;
}

function fitSizeToTD(size, proporcion)
{
    size  = parseInt(size / proporcion);
    return size;
}

//Despues de tomar la iamgen que debe de tener, redimensiona la imagen
//con respecto a la si misma, en caso de haber sido cambiada alguna vez
function initSize()
{
    $('.imagenPrincipal').each(function()
    {
        changeImageZoom(this.id, this.id);
    });
}

/**
 * Si el usuario configura una vista inicial de catalogos, inicializa el link
 * para cambiar el tipo de vista de catalogo
 */
function initKindViewCatalog(idCatalogo)
{

    var url, tipoVista;
    url = $('#urlChangeKindViewCatalog').val();
    tipoVista = $('#tipoVistaCatalogo').val();

    $('#linkKindCatalog').click(function(){

        var vistaPreview = $('#tipoPreview').val();
        if(vistaPreview == undefined)
        {
            vistaPreview = 0;
        }
        else
        {
            vistaPreview = 1;
        }

        $.post(url, {
            'tipoVistaActual':tipoVista,
            'idCatalogo':idCatalogo,
            'edicion':0,
            'preview':vistaPreview
        }, function(data){
            $('#productsStoreData').html(data);
            $('.btn').button();
            initZoom();
            initKindViewCatalog(idCatalogo);
            getGroupTags();
        });
    });
    
}

function changePagCatalog(Url, IdElemento, PagShow, IdSitio, TipoVista, IdCatalogo, EditMode, DesdeTienda)
{
    $.post( Url,
    {
        'idElemento':IdElemento,
        'pagShow':PagShow,
        'idSitio':IdSitio,
        'tipoVista':TipoVista,
        'idCatalogo':IdCatalogo,
        'editMode':EditMode,
        'desdeTienda':parseInt(DesdeTienda)
    },
    function(data)
    {
        $('#bloqueCatalogo_'+IdElemento).html(data);
        $('.btn').button();
        initZoom();
    });
}


/**
 *  Acorta el nombre de la pagina en el menu vertical para que no se empalme
 *  con la siguiente accion
 */
function fixLongNamesVerticalMenu(className,totalLength)
{
    var tmp;
    var trimmed = false;
    var arrayliTag;
    var ajuste = false;

    $('.'+className).each(function()
    {
        arrayliTag = $(this).children('li');
        arrayliTag.each(function()
        {
            ajuste = false;
            trimmed = $(this).children();
            while (trimmed.height() > totalLength)
            {
                ajuste = true;
                tmp = trimmed.text();
                tmp = tmp.substring(0, tmp.length-1);
                trimmed.text(tmp);
            }

            trimmed.css('height',totalLength+'px');
            if(ajuste == true)
            {
                trimmed.text(trimmed.text()+"...");
            }
        });
    });
}
function gallery2()
{
       $('div.navigation').css({'width' : '100px', 'float' : 'left'});
    $('div.content').css('display', 'block');
    // Initially set opacity on thumbs and add
    // additional styling for hover effect on thumbs
    var onMouseOutOpacity = 0.67;
    $('#thumbs ul.thumbs li').opacityrollover({
            mouseOutOpacity:   onMouseOutOpacity,
            mouseOverOpacity:  1.0,
            fadeSpeed:         'fast',
            exemptionSelector: '.selected'
    });

    // Initialize Advanced Galleriffic Gallery
    var gallery = $('#thumbs').galleriffic({
             delay:                     2500,
            numThumbs:                 4,
            preloadAhead:              10,
            enableTopPager:            true,
            enableBottomPager:         false,
            maxPagesToShow:            7,
            imageContainerSel:         '#slideshow',
            controlsContainerSel:      '#controls',
            captionContainerSel:       '#caption',
            loadingContainerSel:       '#loading',
            renderSSControls:          true,
            renderNavControls:         true,
            enableKeyboardNavigation:  false,
            playLinkText:              'Play',
            pauseLinkText:             'Pause',
            prevLinkText:              '&lsaquo; Prev',
            nextLinkText:              'Next&rsaquo;&nbsp;',
            nextPageLinkText:          '&rsaquo;',
            prevPageLinkText:          '&lsaquo;',
            enableHistory:             false,
            autoStart:                 true,
            syncTransitions:           true,
            defaultTransitionDuration: 900,
            onSlideChange:             function(prevIndex, nextIndex) {
                    // 'this' refers to the gallery, which is an extension of $('#thumbs')
                    this.find('ul.thumbs').children()
                            .eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
                            .eq(nextIndex).fadeTo('fast', 1.0);
            },
            onPageTransitionOut:       function(callback) {
                    this.fadeTo('fast', 0.0, callback);
            },
            onPageTransitionIn:        function() {
                    this.fadeTo('fast', 1.0);
            }
    });
    var color=$('#fondoElement').val();
    $('div.galleryTwo').css('background-color',color);
    $('#gallery').css('background-color',color);
}

