/* $Id: nx_compare.js,v 1.19 2011/08/12 06:38:23 payal Exp $ */

/*-------------------------------GLOBAL VARIABLES------------------------------------*/

// Define These Variables into language files of Varios Projects of Nettix
var msgSiteCodeMiss='Site code is missing for comparison';
var msgMaxMinSelectId='Please select at least 2 and maximum 10 vehicles for comparison';
/*-----------------------------------------------------------------------------------*/

var checkedCnt=addCnt=remCnt=0;
var browser=navigator.appName;

/** Create Compare Object */
var Compare={
    maxLen      : 10,   /** Define Maximum Length you want in Compare Modal Box */
    siteCode    : '',   /** Required, According to this, script will create cookie and store ids
                         *  so that you can compare vehicles, bikes etc.etc. from various pages
                         *  eg. compare vehicle between page 2,3,10
                         **/
    c_URL       : '',   /** According to siteCode, URL will be set */
    c_Name      : '',   /** According to siteCode, cookieName willbe generated. */
    stopCompare : 0,    /** to Immidiately Stop Comparison */
    yPos        : 0,
    pHeight     : 0,
    removing    : 0,    /** in case vehicle is removed from compare, no need to getScroll of the page.
                         *  otherwise it will get jumping
                         **/

    /** This method will be called when you initialize Compare object */
    init: function(siteCode)
    {
        this.siteCode=siteCode;
        this.c_Name=siteCode+"_compare";
        this.c_URL='http://'+location.host;
        this.removing=0;
        switch(this.siteCode)
        {
            case 'NA':
            case 'NM':
            case 'NT':
                this.c_URL +='/compareVehicles.php';
                msgMaxMinSelectId=msgSelMinTwoVeh;
                break;
            case 'NV':
                this.c_URL +='/compareBoats.php';
                msgMaxMinSelectId=msgSelMax10Boat;
                break;
             case 'NK':
                this.c_URL +='/compareMachines.php';
                msgMaxMinSelectId=msgSelMinTwoMachine;
                break;
            case 'NH':
                this.c_URL +='/compareApartment.php';
                msgMaxMinSelectId=msgSelMinTwoVeh;
                break;
            default :
                alert(msgSiteCodeMiss);
                this.stopCompare=1;
                break;
        }
    },

    /** Call this function when you need to get checked ids. */
    addToCompare: function(id)
    {
        var cookies = this.getCookie();
        this.getForSaleOnly(cookies+','+id);

        // If same id not exist in Cookie then Enter id into Cookie
        if(cookies.indexOf("," + id) == -1 && cookies.indexOf(id) == -1)
        {
            var arr_c = this.getCookie().split(",");
            if (arr_c.length == this.maxLen)
            {
                alert(msgMaxMinSelectId);
            }
            else
            {
                /** Get Latest cookie */
                var u_Cookie=this.getCookie();
                if(u_Cookie)
                    document.cookie = this.c_Name +"=" + u_Cookie.toString() + "," + id + "; expires= " + this.getExpDt() + "; path=/";
                else
                    document.cookie = this.c_Name +"=" + id.toString() + "; expires= " + this.getExpDt() + "; path=/";
            }
        }
    },

    /** The purpose of this function is to reset cookie to store FOR SALE ids only.*/
    getForSaleOnly: function(ids)
    {
        jQuery.get(this.c_URL+'?ajxifrm=A&action=updateCookie&compare='+ids)
    },

    /** this function will get latest cookie data for compare list */
    getCookie: function()
    {
        var c_nm=this.c_Name;

        /** check if cookie not created, not found or expired then create it. */
        if(document.cookie.indexOf((c_nm)) == -1)
            document.cookie = c_nm +"="+ '' + "; expires= " + this.getExpDt() + "; path=/";

        var start = document.cookie.indexOf(c_nm+"=");
        var len = start+c_nm.length+1;
        var end = document.cookie.indexOf(';',len);
        end = (end == -1) ? document.cookie.length : end;

        return unescape(document.cookie.substring(len,end));
    },

    /** This function will return Expiry date you want to set for cookie */
    getExpDt: function()
    {
        var now = new Date();
        now.setYear(now.getFullYear() + 1); // Set expire time for 1 year
        return now.toGMTString();
    },

    /** Modal box Display through this function */
    getCompareModal: function()
    {
        var intVal=Array();
        var tmpIntVal=0;
        var pars='?ajxifrm=A&compare='+this.getCookie();
        var ele=gebi('compare_modal');
        var flag=1;
        var prevState='';
        jQuery.fn.colorbox({
            href:this.c_URL+pars,onComplete:function(){
            for(var i = 0; i < intVal.length; i++)
                try{clearInterval(intVal[i])}catch(e){}
            }
        });
    },

    /** will get Scroll of the page */
    getScroll: function()
    {
        if (self.pageYOffset)
            this.yPos = self.pageYOffset;
        else if (document.documentElement && document.documentElement.scrollTop)
            this.yPos = document.documentElement.scrollTop;
        else if (document.body)
            this.yPos = document.body.scrollTop;

        return this.yPos;
    },

    /** Get the inner height of the page */
    getHeight: function()
    {
        if (self.innerHeight) // all except Explorer
            this.pHeight = self.innerHeight;
        else if (document.body) // other Explorers
            this.pHeight = document.body.clientHeight;
        // Explorer 6 Strict Mode
        else if (document.documentElement && document.documentElement.clientHeight)
            this.pHeight = document.documentElement.clientHeight;

        return this.pHeight;
    },

    /** Remove from Compare box */
    remCompare: function(id)
    {
        try
        {
            var comp=document.getElementById('compare_modal');
            var removeObjs=this.getElementsByClass(id, comp,'td');
            var removeLength=removeObjs.length;
            this.removing=1;

            /** Now Remove Id from cookie */
            this.removeIdFromCookie(id);

            for(var i=0; i < removeLength; i++)
            {
                removeObjs[i].style.display="none";
            }
        }
        catch(e){}
    },

    /** in IE, there was some problems with getting class name by id, so put this function */
    getElementsByClass: function(searchClass,node,tag)
    {
        var classElements = new Array();
        if (node == null) node = document;
        if (tag == null) tag = '*';
        var els = node.getElementsByTagName(tag);
        var elsLen = els.length;
        var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
        for (i = 0, j = 0; i < elsLen; i++)
        {
            if (pattern.test(els[i].className))
            {
                classElements[j] = els[i];
                j++;
            }
        }
        return classElements;
    },

    /** Remove given id from compare cookie */
    removeIdFromCookie: function(id)
    {
        var rem_Id=''; // for Remaining Ids.
        var cookies = this.getCookie().split(",");

        for(var i=0; i < cookies.length; i++)
        {
            /** Only remove the id which is clicket for remove */
            if(id != cookies[i])
                rem_Id +=cookies[i]+',';
        }

        rem_Id=rem_Id.substr(0,(rem_Id.length-1));

        /** store Remaining id (rem_Id) into Cookie */
        document.cookie = this.c_Name +"=" + rem_Id.toString() + "; expires= " + this.getExpDt() + "; path=/";

        gebi('add-more').style.display="";

        try{
            if(rem_Id.length > 0)
                this.getCompareModal(); // Get Compare Modal again for most/least attractive in set */
            else
                closeCompareWindow();
        }
        catch(e){}
    }
}

/** this function will create compare object and display comparison in modal box */
function compare(siteCode,id)
{
    if(siteCode)
    {
        Compare.init(siteCode);

        if(!Compare.stopCompare)
            Compare.addToCompare(id);

        if(Compare.stopCompare == 0)
            Compare.getCompareModal();
    }
    return false;
}

/** Function to remove vehicles from compare window */
function removeCompare(siteCode,id)
{
    gebi('reload-compare').style.display='inline';
    Compare.init(siteCode);
    Compare.remCompare(id);

    return false;
}

/** Function to close compare window */
function closeCompareWindow()
{
    jQuery.fn.colorbox.close();
}

/** replace document.getElementById with this function */
function gebi(i)
{
    return document.getElementById(i);
}

/************************** Start functionality for DropDown Menu for Compare links **************************/
var arrShowHide=Array();
function showHideCompare(id)
{
    var id_ele=id;
    var p=gebi('parent-'+id);
    var c=gebi('child-'+id);

    p["at_parent"]=p.id;
    c["at_parent"]=p.id;
    p["at_child"]=c.id;
    c["at_child"]=c.id;

    p.onmouseover=at_show;
    p.onmouseout=at_hide;
    c.onmouseover=at_show;
    c.onmouseout=at_hide;
    if(!arrShowHide[id])
        setTimeout(function(){at_show_aux('parent-'+id_ele,'child-'+id_ele);},100);

    arrShowHide[id]=1;
}

function at_show_aux(parent, child)
{
    var p = gebi(parent);
    var c = gebi(child );

    c["show_timeout"] = setTimeout("gebi('"+c.id+"').style.display = 'block'", 400);
}

/** to show Compare drop down Menu */
function at_show()
{
    var p = gebi(this["at_parent"]);
    var c = gebi(this["at_child" ]);

    at_show_aux(p.id, c.id);
    try{clearTimeout(c["at_timeout"]);}catch(e){}
}

/** to Hide Compare drop down Menu */
function at_hide()
{
    var p = gebi(this["at_parent"]);
    var c = gebi(this["at_child" ]);

    c["at_timeout"] = setTimeout("gebi('"+c.id+"').style.display = 'none'", 500);
    try{clearTimeout(c["show_timeout"]);}catch(e){}
}
/************************** End functionality for DropDown Menu for Compare links **************************/

/**
 * @name comm_submitFav
 * @desc Common SubmitFav function for all netti sites
 *
 * @param thisV string 'remove' or null, to add to Favorite or remove from favorite, also gether if we add Fav from Compare modal
 * @param id_ad int id of ad like id_car, id_bike
 * @param site char(2) site code for parameters
 */
function comm_submitFav(thisV,id_ad,site)
{
    var id_msg=opt=pars='',sub_url=location.href;

    if(thisV != 'remove')
    {
        opt='Fav';

        if(thisV == 'compare')
            id_msg=id_ad+'_msg_Addfav';
        else
            id_msg=id_ad+'-msg';

        /** effect is give on this id so better to set it display as none. */
        if (_isNLSite == 0)
        {
            gebi(id_msg).style.display="block";

            gebi(id_msg).innerHTML='<img src="'+gebi('loadingImg').src+'" alt="" />';
        }

        switch(site)
        {
            case 'NA':
                pars = 'opt='+opt+'&fav_car[]='+id_ad;
                break;
            case 'NM':
                pars= 'opt='+opt+'&fav_bike[]='+id_ad;
                break;
            case 'NT':
                pars= 'opt='+opt+'&fav_travel_truck[]='+id_ad;
                break;
            case 'NV':
                pars= 'opt='+opt+'&fav_boat[]='+id_ad;
                break;
            case 'NK':
                pars= 'opt='+opt+'&fav_machine[]='+id_ad;
                break;
            case 'NH':
                pars= 'opt='+opt+'&fav_house[]='+id_ad;
                break;
            case 'NP':
                pars= 'opt='+opt+'&fav_part[]='+id_ad;
                break;
            default :
                alert(msgSiteCodeMiss);
                return false;
                break;
        }
        jQuery.post(sub_url,pars,function(data){
            arr = data.split("#");
            if(arr[0] != '0')
            {
                 try{
                     jQuery('#favorite_cnt').html('(' + arr[0] + ')');
                     jQuery('#favorite_cnt_end').html('(' + arr[0] + ')');
                 }
                 catch(e){alert(e);}
            }
            if(_isNLSite == 1)
                notificationBox(msgAddFavOne);
            else
            {
                jQuery('#'+id_msg).html(msgAddFav);
                jQuery('#'+id_msg).fadeOut(3000);
            }
        });
    }
    else
    {
        var _f = document.fav;
        var i,flag='N',checked_value,img_id='';
        var flag_single='N';
        if(id_ad && !isNaN(id_ad))
            flag_single='Y';

        for(i=1; i < _f.length; i++)
        {
            if(_f.elements[i].type == 'checkbox')
            {
                if(flag_single == 'Y' && _f.elements[i].value==id_ad)
                {
                    _f.elements[i].checked=true;
                    _f.elements[i].value=id_ad;
                    flag='Y';
                    break;
                }
                if(_f.elements[i].checked || flag_single == 'Y')
                {
                    flag='Y';
                    continue;
                }
            }
        }
        if(flag != 'Y')
        {
            alert(msgSelectAtLeastOne);
            return false;
        }

        _f.opt.value='Rem';

        /* NOTE : IE6 is slower in JS Execution, so I Put this delay for form submit. */
        if(_isNLSite == 1)
        {
            _f.ajxifrm.value = 'A';
            var pars=jQuery(_f).serialize();
            jQuery.post('http://'+location.hostname+'/listFavorite'+fileMidName+'.php',pars,function(data){
                _f.opt.value='';
                ajaxPostUpdater("listFavorite"+fileMidName+".php");

                if(data.match('@#@')) {
                    var respArr = data.split('@#@');
                    jQuery('#favorite_cnt').html('('+respArr[0]+')');
                    jQuery('#favorite_cnt_end').html('('+respArr[0]+')');
                    notificationBox(respArr[1]);
                }
                else {
                    jQuery('#favorite_cnt').html('(0)');
                    jQuery('#favorite_cnt_end').html('(0)');
                    notificationBox(data);
                }
            });
            return false;
        }
        else
            setTimeout('document.fav.submit()',100);
    }
    return false;
}
