DHTML_modalMessage=function(){var a;var g;var d;var l;var f;var c;var b;var m;var j;var k;var i;var e;var n;var h;this.url="";this.htmlOfModalMessage="";this.layoutCss="syi.css";this.height=400;this.width=100;this.cssClassOfMessageBox=false;this.shadowDivVisible=true;this.shadowOffset=4;this.MSIE=false;if(navigator.userAgent.indexOf("MSIE")>=0){this.MSIE=true}};DHTML_modalMessage.prototype={setSource:function(a){this.url=a},setHtmlContent:function(a){this.htmlOfModalMessage=a},setSize:function(b,a){if(b){this.width=b}if(a){this.height=a}},setCssClassMessageBox:function(a){this.cssClassOfMessageBox=a;if(this.divs_content){if(this.cssClassOfMessageBox){this.divs_content.className=this.cssClassOfMessageBox}else{this.divs_content.className="modalDialog_contentDiv"}}},setShadowOffset:function(a){this.shadowOffset=a},display:function(){if(!this.divs_transparentDiv){this.__createDivs()}this.divs_transparentDiv.style.display="block";this.divs_content.style.display="block";this.divs_shadow.style.display="block";if(this.MSIE){this.iframe.style.display="block"}this.__resizeDivs();window.refToThisModalBoxObj=this;setTimeout("window.refToThisModalBoxObj.__resizeDivs()",150);this.__insertContent()},setShadowDivVisible:function(a){this.shadowDivVisible=a},close:function(){this.divs_transparentDiv.style.display="none";this.divs_content.style.display="none";this.divs_shadow.style.display="none";if(this.MSIE){this.iframe.style.display="none"}},addEvent:function(b,a,c,d){if(!d){d=""}if(b.attachEvent){b["e"+a+c+d]=c;b[a+c+d]=function(){b["e"+a+c+d](window.event)};b.attachEvent("on"+a,b[a+c+d])}else{b.addEventListener(a,c,false)}},__createDivs:function(){this.divs_transparentDiv=document.createElement("DIV");this.divs_transparentDiv.style.left="0px";this.divs_transparentDiv.style.top="0px";this.divs_transparentDiv.style.position="absolute";this.divs_transparentDiv.style.opacity=0.6;this.divs_transparentDiv.style.filter="alpha(opacity=60)";this.divs_transparentDiv.style.backgroundColor="#000";this.divs_transparentDiv.style.zIndex=1000;this.divs_transparentDiv.id ="shadow_map_vip";$(this.divs_transparentDiv).onclick=closeMessage;document.body.appendChild(this.divs_transparentDiv);this.divs_content=document.createElement("DIV");this.divs_content.className="modalDialog_contentDiv";this.divs_content.id="DHTMLSuite_modalBox_contentDiv";this.divs_content.style.zIndex=100000;if(this.MSIE){this.iframe=document.createElement('<IFRAME src="about:blank" frameborder=0>');this.iframe.style.zIndex=90000;this.iframe.style.position="absolute";document.body.appendChild(this.iframe)}document.body.appendChild(this.divs_content);this.divs_shadow=document.createElement("DIV");this.divs_shadow.className="modalDialog_contentDiv_shadow";this.divs_shadow.style.zIndex=95000;document.body.appendChild(this.divs_shadow);window.refToModMessage=this;this.addEvent(window,"scroll",function(a){window.refToModMessage.__repositionTransparentDiv()});this.addEvent(window,"resize",function(a){window.refToModMessage.__repositionTransparentDiv()})},__getBrowserSize:function(){var a,b;if(self.innerHeight){a=self.innerWidth;b=self.innerHeight}else{if(document.documentElement&&document.documentElement.clientHeight){a=document.documentElement.clientWidth;b=document.documentElement.clientHeight}else{if(document.body){a=document.body.clientWidth;b=document.body.clientHeight}}}return[a,b]},__resizeDivs:function(){var e=Math.max(document.body.scrollTop,document.documentElement.scrollTop);if(this.cssClassOfMessageBox){this.divs_content.className=this.cssClassOfMessageBox}else{this.divs_content.className="modalDialog_contentDiv"}if(!this.divs_transparentDiv){return}var d=Math.max(document.body.scrollTop,document.documentElement.scrollTop);var c=Math.max(document.body.scrollLeft,document.documentElement.scrollLeft);window.scrollTo(c,d);setTimeout("window.scrollTo("+c+","+d+");",10);this.__repositionTransparentDiv();var f=this.__getBrowserSize();var b=f[0];var h=f[1];this.divs_content.style.width=this.width+"px";this.divs_content.style.height=this.height+"px";var a=this.divs_content.offsetWidth;var g=this.divs_content.offsetHeight;this.divs_content.style.left=Math.ceil((b-a)/2)+"px";this.divs_content.style.top=(Math.ceil((h-g)/2)+e)+"px";if(this.MSIE){this.iframe.style.left=this.divs_content.style.left;this.iframe.style.top=this.divs_content.style.top;this.iframe.style.width=this.divs_content.style.width;this.iframe.style.height=this.divs_content.style.height}this.divs_shadow.style.left=(this.divs_content.style.left.replace("px","")/1+this.shadowOffset)+"px";this.divs_shadow.style.top=(this.divs_content.style.top.replace("px","")/1+this.shadowOffset)+"px";this.divs_shadow.style.height=g+"px";this.divs_shadow.style.width=a+"px";if(!this.shadowDivVisible){this.divs_shadow.style.display="none"}},__repositionTransparentDiv:function(){this.divs_transparentDiv.style.top=Math.max(document.body.scrollTop,document.documentElement.scrollTop)+"px";this.divs_transparentDiv.style.left=Math.max(document.body.scrollLeft,document.documentElement.scrollLeft)+"px";var b=this.__getBrowserSize();var a=b[0];var c=b[1];this.divs_transparentDiv.style.width=a+"px";this.divs_transparentDiv.style.height=c+"px"},__insertContent:function(){if(this.url){ajax_loadContent("DHTMLSuite_modalBox_contentDiv",this.url)}else{this.divs_content.innerHTML=this.htmlOfModalMessage}}};messageObj=new DHTML_modalMessage();messageObj.setShadowOffset(3);function displayMessage(a){messageObj.setSource(a);messageObj.setCssClassMessageBox(false);messageObj.setSize(400,200);messageObj.setShadowDivVisible(true);messageObj.display()}function processEmbed(c){var b=document.getElementsByTagName("embed");for(var a=0;a<b.length;a++){try{b[a].style.visibility=c}catch(d){}}}function displayStaticMessage(e,c,b,d){if(!b){b=400}if(!d){d=120}messageObj.setSize(b,d);messageObj.setHtmlContent(e);messageObj.setCssClassMessageBox(c);messageObj.setSource(false);messageObj.setShadowDivVisible(true);processEmbed("hidden");messageObj.display()}function closeMessage(){processEmbed("visible");messageObj.close()};

$.url = function(url) {return $("meta[name='Identifier-URL']").attr('content')+url.substr(1);}


$(window).load(function(){    
    $(".active-image").click(function(){ 
        var heightImg = $(this).attr('height');
        if(heightImg!= undefined){
            var srcImg = $(this).attr('href');
            var title = $(this).attr('title');
            $('div.imagen').html('<img src="'+srcImg+'" title="'+title+'">');
            var $img = $('div.imagen img');
            var hDiv = $('.imagen').height();
            var maxHeight = 413;
            if(heightImg >= maxHeight){
                heightImg = 413;
            }
            if(heightImg < hDiv && heightImg != '0'){
                var topMargin = (hDiv/2) - heightImg/2 +"px";
                $img.css('margin-top',topMargin);
            }
        }else{
            $('div.imagen img').css('margin-top','0px');
        }
        return false;
    });
});

/**
 ** @desc: load the first image of thumb horizontal 
 **/
function loadFirst() {
    var heightImg = $('a#firstImg').attr('height');
    if(heightImg != undefined){
        var srcImg = $('#firstImg').attr('href');
        var title = $('#firstImg').attr('title');
        var $img = $('a#firstImg img');
        var hDiv = $('.imagen').height();
        var maxHeight = 413;
        if(heightImg >= maxHeight){
            heightImg = 413;
        }
        $('div.imagen').html('<img src="'+srcImg+'" title="'+title+'">');
        if(heightImg < hDiv && heightImg != '0'){
            var topMargin = (hDiv/2) - heightImg/2 +"px";
            $('div.imagen img').css('margin-top',topMargin);
        }else{
            $('div.imagen img').css('margin-top','0px');
        }
    }else{
        $('div.imagen img').css('margin-top','0px');
    }
}

$(document).ready(function() {
    
    
    /***** thumb cycle  ****/ 
    $('#slideshow').cycle({
            fx:     'fade',
            speed:  'fast',
            timeout: 0,
            pager:  '#navSlider',
            next:   '#next2, #slideshow', 
            prev:   '#prev2',
            after:   onAfter,
            pagerAnchorBuilder: function(idx, slide) {
                    // return sel string for existing anchor
                    return '#navSlider li:eq(' + (idx) + ') a';
            }
    });

    function onAfter(curr, next, opts) {
            var curPos = $('.activeSlide a').position();
            var curSliderPos = $('#imageSlider #navSlider').position();
            if(curPos != null){
                    if((curPos.left + curSliderPos.left) > 470){
                            var moveTo = (curPos.left) - (470-curSliderPos.left);
                            console.log(moveTo);
                            $("#navSlider").animate({"left": "-="+moveTo+"px"}, "fast");
                    }
                    if((curPos.left + curSliderPos.left) < 0){
                            var moveTo = (curPos.left) + (curSliderPos.left);
                            $("#navSlider").animate({"left": "-="+moveTo+"px"}, "fast");
                    }
            }
            //var caption = 'Foto ' + (opts.currSlide + 1) + ' de ' + opts.slideCount + '';
            //$('#caption').html(caption);
    }

    //Resize div imageSlider
    var maxHeightSize = $('#maxHeightSlide').attr('name');
    $('#imageSlider').css('height',maxHeightSize +'px');
    /*** end thumb cycle **/
    
    //loadFirst(); 
    $('#shadow_map_vip').live("click", function(){closeMessage();}); //close Google Maps
    if($("#classifiedActive").val() == 0){
        var legend = "<div class='show-advertise'><p> Este anuncio fue deshabilitado. Es probable que la operación haya sido concretada o finalizada. Vea anuncios relacionados a continuación del mismo. <br/> <a href='#show'>Ver Anuncio</a></p></div>";
       $(".classified_intro").prepend(legend);
    }

    $("#phoneId").click(function() {
        var legend= "<p class='phoneMessenger'><span class='trianglePhone'></span>Cuando llame diga que vio el numero en alaMaula</p>";
         $.ajax({
              url: $.url('/classifieds/countClickPhone/'),
              type: "GET",
              data: ({id : this.getAttribute('classified')}),
              cache: false,
              success: function(data) {
                $('#phoneNumber .phoneHidden').text(data);
                $(legend).appendTo('#phoneNumber');
              }
          });
          return false;
    });

    $('#lnkReport').click(function(){
        $('#divReport').toggle();
        return false;
    });

    $(".lnkReportItem").click(function() {
        var _type = (this.id).split("-");
        if(_type[1] != null){
            $.ajax({
                url: $.url('/classifieds/report_classified/'),
                type: "GET",
                data: ({classified_id : this.getAttribute('classified'),
                    type : _type[1]}),
                cache: false,
                success: function(data) {
                    $('#divReport').html(data);
                }
            });
        }
        return false;
    });
    
    $("#btnComment").click(function() {
            if(validateCommentForm()){
                $("#question-submit").html('<img src="'+$.url('/img/') + 'ajax-loader.gif"/>');
                $.ajax({
                    url: $.url('/classifieds/add_comment_post/'),
                    type: "GET",
                    data: ({
                        classified_id : this.getAttribute('classified'),
                        name: $('#ClassifiedAddCommentName').attr('value'),
                        body: $('#ClassifiedAddCommentBody').attr('value'),
                        email: $('#ClassifiedAddCommentEmail').attr('value'),
                        private_msg: $('#ClassifiedAddCommentPrivate').attr('checked')
                    }),
                    cache: false,
                    success: function(data) {
                        $('#box-comments').html(data);
                    }
                });
            }
        return false;
    });        
    
    /** Related Click Classified zone **/
    $('.classifieds_related .classified-summary').click(function(){
    var locationClassified = $(this).find('.classified-body > h4 > a').attr('href');
        if(locationClassified!= undefined){
            window.location=''+locationClassified;return false;
        }
    });
    
    $('.classifieds_related .classified-summary .classified-details span.actions > a').click(function(){
        var locationCategory = $(this).attr('href');
        if(locationCategory!=undefined){
            window.location=''+locationCategory;return false;
        }
    });
    
    /**** right column Related Click Classified zone **/
    $('.box-gray .classified-summary').click(function(){
        var locationClassified = $(this).find('.classified-body > a').attr('href');
        if(locationClassified!= undefined){    
            window.location=''+locationClassified;return false;
        }
    });
    

});

function checkCommentForm(){
        return false;
}

function validateCommentForm(){ 
    var name = $('#ClassifiedAddCommentName').attr('value');
    var body = $('#ClassifiedAddCommentBody').attr('value');
    var email = $('#ClassifiedAddCommentEmail').attr('value');    
    var msg = "";
    
    if(name.length < 3){
        msg = "El Campo nombre tiene que tener al menos 3 caracteres; por favor complete el campo. \n\r"
    } else if(body.length == 0){
        msg = "No puede enviar un comentario vacío; por favor, complete en el lugar indicado (min. 10 caracteres) \n\r"
    } else if(body.length < 10){
        msg = "No puede enviar un mensaje menor a 10 caracteres; por favor, complete en el lugar indicado \n\r"
    }
       
    if(email.length == 0){
        msg += "Debe indicar un mail de contacto con formato válido (mail@servidor.com)"
    }else if(checkEmail(email)==false){
        msg += "El mail no tiene un formato válido (mail@servidor.com)";
    }
    if(msg.length > 0){
        alert(msg);
        return false;
    }
    return true;
}

/**
 * @retun false otherwise nothing
 */
function checkEmail(mail) { 
    var email = mail;
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (!filter.test(email)) {
        return false;
    }
}

function launchMap(lat, lng, city, zoom) {
    if(lat != 0 && lng != 0){
        setWaypoint(lat, lng, zoom);
    } else {
        showAddress(city,zoom);
    }
}

function setWaypoint(lat, lng, zoom){
    if (GBrowserIsCompatible()) {
        point = new GLatLng(lat, lng);
        map = new GMap2(document.getElementById("map_popup"));
        map.addControl(new GLargeMapControl);
        map.setCenter(point, zoom);
        marker = new GMarker(point);
        map.addOverlay(new GMarker(point));
    }
}

function loadMapOnDemand(lat, lng, city){
    displayStaticMessage("<div id='map_popup' style='width:680px;height:480px;margin:0 auto;'></div><div class='float_r pt8'><a href='javascript:void(null);' onClick='closeMessage();'>Cerrar</a></div>", 'modalDialog_vip_map', 690, 500);
    google.load("maps", "2", {"other_params":"sensor=false", "callback" : function(){    
        launchMap(lat, lng, city, 15);
        document.onunload=GUnload;
    }});
}

function showAddress(address, zoom) {
    var geocoder = new GClientGeocoder();
    geocoder.getLatLng(address,function(point){
        if (!point) {
            return false;
        } else {
            if (point != false && point != 'undefined') {
                map = new GMap2(document.getElementById("map_popup"));
                map.setCenter(point, zoom);
                map.addControl(new GLargeMapControl);
            }
        }
    }
  );
}

function alertBox(msg){
    var position = $(".box-comments").offset();
    position.left -= 220;
    position.top += 50;
    $.blockUI({
    title: '',
    message: '<p class="msg">'+msg+'</p>',
    fadeIn: 700,
    fadeOut: 700,
    timeout: 4000,
    showOverlay: false,
    centerY: false,
    css: {
            position:'absolute',
            width: '200px',
            top: position.top + 'px',
            left: position.left + 'px',
            border: '1px solid #2683CF',
            padding: '5px',
            color:'#454545',
            fontweight:'bold',
            backgroundColor: '#EFF7FF',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            opacity: 0.8

        }
    });
    $('html, body').animate({scrollTop: 0}, 0);
    $('#ClassifiedAddCommentBody').focus();
}	
