/* $Id: common.js,v 1.125 2011/08/24 06:45:53 tejash Exp $ */

var baseUrl='http://'+location.hostname;
var _isNLSite = 0;
if(location.hostname.match(/nettiauto/i) || location.hostname.match(/nettimoto/i) ||
   location.hostname.match(/nettivene/i) || location.hostname.match(/nettikone/i)  || location.hostname.match(/nettivaraosa/i))
    _isNLSite = 1;

if(!window.location.href.match(/extra\/admin/i))
{
    jQuery('#fb_connect').mouseover(function(){
        $seconds = 0;
        $timer = 0;
        fbToolTip(fb_benefit_fbc,fb_fast_reg,fb_auto_reg,fb_fast_login,fb_one_click,fb_no_auto_share,fb_no_auto_post);
    }).mouseout(function(){
        clearTimeout($seconds);
        jQuery('.fb_toolTipWrapper').fadeOut(50);
    });
}

/** Function which checks whether given email is valid or not */
function emailInvalid(s)
{
    if(s.match(/^\w+([\.\+]?[-]{0,2}\w+)*[\.]?[-]?@\w+([\.-]?\w+)*(\.\w{2,4})+$/i))
        return true;
    else
        return false;
}
/** Function which checks whether given url address is valid or not */
function urlInvalid(s)
{
    if(!(s.match(/^http:\/\/[a-zA-Z\d]+([_|\.-][a-zA-Z\d~-]{1,})*\.([a-z]{2,4})(\/[a-zA-Z\d~-]{1,}[_|\.]{0,1}[a-zA-Z\d~]{1,}\/?)*([_|\.][a-zA-Z\d~-]{1,})*(\?)?([a-zA-Z\d=~])*$/i)
        || s.match(/^ftp:\/\/[a-zA-Z\d]+([_|\.][a-zA-Z\d~-]{1,})*\.([a-z]{2,4})(\/[a-zA-Z\d~-]{1,}[_|\.]{0,1}[a-zA-Z\d~]{1,}\/?)*([_|\.][a-zA-Z\d~]{1,})*(\?)?([a-zA-Z\d=~])*$/i)))

        return false;
    else
        return true;
}
/** Function to check phone,fax,mobile for finland country */
function check(s)
{
    if(!s.match(/^[0-9\s\+-]{5,25}$/) )
        return false;
    else
        return true;
}
/** Function to check whether given string is really empty or not */
function isblank(s)
{
    for(var i=0; i < s.length; i++)
    {
        var c=s.charAt(i);

        if((c != ' ') && (c != "\n") && (c != "\t"))
            return false;
    }
    return true;
}
/** Function to check Password string, various rules are followed */
function checkPasswd(s)
{
    if(s.match(/^[a-zA-Z0-9åÅäÄöÖüÜÁÀÉÈÒÓÙÚáàèéòóùúÝìíýÌÍ´_.-]{4,12}$/))
        return true;

    return false;
}
/** Function to check the alphanumeric characters. */
function checkAlphaNumeric(s)
{
    if(!s.match(/^[0-9a-zA-ZåÅäÄöÖüÜÁÀÉÈÒÓÙÚáàèéòóùúÝìíýÌÍ´\s-]{1,100}$/))
        return false;
    else
        return true;
}
/** Function to check First-Last name values when it is entered as full name */
function checkFullName(s)
{
    if(!s.match(/^[a-zA-ZåÅäÄöÖüÜÁÀÉÈÒÓÙÚáàèéòóùúÝìíýÌÍ´_\s-]{1,50}$/))
        return false;
    else
        return true;
}
/** Function to check First-Last name values */
function checkName(s)
{
    if(!s.match(/^[a-zA-ZåÅäÄöÖüÜé´ÁÀÉÈÒÓÙÚáàèéòóùúÝìíýÌÍ-]{1,30}$/))
        return false;
    else
        return true;
}
/** Function to check hobby/reference values */
function checkHobbyRef(s)
{
    if(!s.match(/^[0-9a-zA-ZåÅäÄöÖüÜÁÀÉÈÒÓÙÚáàèéòóùúÝìíýÌÍ_:;@´()\s\+\,'.-]{1,250}$/))
        return false;
    else
        return true;
}
/** Function to check address/contact time values */
function checkAddContTime(s)
{
    if(!s.match(/^[0-9a-zA-ZåÅäÄöÖüÜÁÀÉÈÒÓÙÚáàèéòóùúÝìíýÌÍ_´\/:()\s\,'.!-]{1,250}$/))
        return false;
    else
        return true;
}
/** Function to check city values */
function checkCity(s)
{
    if(!s.match(/^[0-9a-zA-ZåÅäÄöÖüÜÁÀÉÈÒÓÙÚáàèéòóùúÝìíýÌÍ_´:\s\,-]{1,250}$/))
        return false;
    else
        return true;
}
/** Function to check zip values */
function checkZip(s)
{
    if(!s.match(/^[0-9a-zA-Z]{1,250}$/))
        return false;
    else
        return true;
}
/** Function to check loginid string, various rules are followed. */
function checkLogin(s)
{
    var dummyWords=new Array('admin','webmaster','help','helpdesk','user','dealer','dummy','nettiauto',
                                'nettimoto','nettivene','nettivaraosa','nettimokki','nettikone',
                                'nettiasunto','nettimarkkina','nettikaravaani');
    if(!(s.match(/^[a-zA-Z0-9åÅäÄöÖüÜÁÀÉÈÒÓÙÚáàèéòóùúÝìíýÌÍ´_]{4,12}$/)))
        return msgUserid;
    else
    {
        s=s.toLowerCase();
        for(i=0; i < dummyWords.length; i++)
        {
            if(s == dummyWords[i])
            {
                return msgResdId;
                break;
            }
        }
    }
    return 1;
}
/** Function to check characters length of word */
function isLong(eleValue,sep,len)
{
    if (eleValue == '')
        return true;
    else
    {
        if(sep == ' ')
            tempValue=eleValue.split(/\s+/);
        else
            tempValue=eleValue.split(sep);

        for(var i=0; i < tempValue.length; i++)
        {
            if(tempValue[i].length > len)
            {
                return 0;
                break;
            }
        }
    }
    return 1;
}
/** Function to check SSN number validation in Finland country */
function checkSsn(p)
{
    lChar=new Array('A','B','C','D','E','F','H','J','K','L','M','N','P','R','S','T','U','V','W','X','Y','Z');

    if(!(p.match(/^[0-9]{6}-[0-9]{3}[0-9a-zA-Z]{1}$/)))
        return false;
    else
    {
        ssn=p.replace('-','');
        first=ssn.substr(0,9);
        start1=ssn.substr(0,6);
        middle=ssn.substr(6,3);
        last=ssn.substr(9,1);
        remin=(first % 31);

        if(remin >= 0 && remin <= 9)
            rightChar=remin;
        else
            rightChar=lChar[remin-10];

        rightSSN=start1+'-'+middle+rightChar;

        if(rightSSN == p)
            return true;
        else
            return false;
    }
    return false;
}
/**
Function to give the user a message to login to the site, when he tries to access the feature
which is only for registered memeber.
*/
function loginWarning(msgWar,curTxt)
{
    if(!isblank(curTxt))
       alert(msgWar);
}
/** Function to confirm the cancel event and redirect to given file or home page */
function confirmCancel(valMsg,valFile)
{
    if(valMsg != '')
    {
        if(confirm(valMsg))
        {
            if(valFile)
                location.href=valFile;
            else
                location.href=location.protocol+'//'+location.hostname;
        }
        else
            return false;
    }
    else
    {
        if(valFile != '')
            location.href=valFile;
        else
            location.href=location.protocol+'//'+location.hostname;
    }
}

function openVote(url)
{
    jQuery.fn.colorbox({overlayClose:false,escKey:false,href:_su+"/"+url});
}

/** Function to open new pop up window with fixed size */
function openWin(varUrl,varTitle)
{

    var h=screen.height;
    h=h-80;

    var myfeatures='directories=no,location=no,menubar=no,status=yes,titlebar=no,toolbar=no,resizable=yes,scrollbars=yes,width=730,height='+h+',left=0,top=0';

    if(varTitle == '')
        varTitle='new';

    var newWin=window.open(varUrl,varTitle,myfeatures);
    newWin.focus();
}
/** Function to open new pop up window with foto  size */
function openWinfoto(varUrl,varTitle)
{

    var h=screen.height;
    h=h-80;

    var myfeatures='directories=no,location=no,menubar=no,status=yes,titlebar=no,toolbar=no,resizable=yes,scrollbars=yes,width=1300,height='+h+',left=0,top=0';

    if(varTitle == '')
        varTitle='new';

    var newWin=window.open(varUrl,varTitle,myfeatures);
    newWin.focus();
}

/** Function to open the new window with given width and height */
function openNewWin(varUrl,w,h,varTitle,varLeft,varTop)
{
    var varLeft,varTop;
    if(varLeft == '')
        varLeft='0';

    if(varTop == '')
        varTop='0';

    var myfeatures='width='+w+',height='+h+',left='+varLeft+',top='+varTop+',directories=no,location=no,menubar=no,status=yes,titlebar=no,toolbar=no,resizable=no,scrollbars=no';

    if(varTitle == '')
        varTitle='new';

    var newWin=window.open(varUrl,varTitle,myfeatures);
    newWin.focus();
}
/** Function to change the sitelanguage for given form. */
function changeLanguage(frm)
{
    if(frm.sitelang.value == 1)
        frm.sitelang.value=2;
    else
        frm.sitelang.value=1;

    frm.submit();
    return false;
}
/** Function to change the class name for given id elemente. */
function changeClass(id,cls)
{
    if(document.getElementById(id).className == 'listing_sel')
        document.getElementById(id).className=cls;
    else
        document.getElementById(id).className='listing_sel';
}
/**
Function blinkingText_1() blinkingText_2()
blink the text in given id with different two class and No. of time to blink.
idName=name othe tag id,
className1=Class name that change from one to other,
className2=Class name that display text in original,
nCount=Number of time to blink,
bCount=Take blinking counter so, do not pass from main function call.
*/
function blinkingText_1(idName,className1,className2,nCount,bCount)
{
    if(nCount == '' || isNaN(nCount))
        nCount=3;

    if(bCount == '' || isNaN(bCount))
        bCount=0;

    bCount++;

    document.getElementById(idName).className=className1;
    setTimeout('blinkingText_2("'+idName+'","'+className1+'","'+className2+'","'+nCount+'","'+bCount+'");',500);
}
/** Function call from 'blinkingText_1' and vice versa */
function blinkingText_2(idName,className1,className2,nCount,bCount)
{
    document.getElementById(idName).className=className2;

    if(bCount < nCount)
        setTimeout('blinkingText_1("'+idName+'","'+className1+'","'+className2+'","'+nCount+'","'+bCount+'");',500);
}

/** Function to submit navigation*/
function submitNav(pno,sortBy,ono)
{
    document.nav.page.value=pno;
    document.nav.sortCol.value=sortBy;
    document.nav.ord.value=ono;
    document.nav.submit();
}

/** Sort displaying vehicle list page according to specified arguments. */
function sortForm(col,ord)
{
    document.sortl.sortCol.value=col;
    document.sortl.ord.value=ord;
    if(col!='' && ord!='' && document.sortl.list_sort_col)
        document.sortl.list_sort_col.value=col+'_'+ord;
    document.sortl.submit();
}

/** Sort displaying vehicle list page according to specified arguments. */
function sortListForm(val)
{
    if(val.match(/_ASC/i))
    {
        document.sortl.sortCol.value = val.replace('_ASC','');
        document.sortl.ord.value='ASC';
    }
    else
    {
        document.sortl.sortCol.value = val.replace('_DESC','');
        document.sortl.ord.value='DESC';
    }
    document.sortl.list_sort_col.value=val;
    document.sortl.submit();
}

/** Sort displaying vehicle list page according to specified arguments. */
function sortListFormSDS(val,frm)
{
    if(val.match(/_ASC/i))
    {
        frm.sortCol.value = val.replace('_ASC','');
        frm.ord.value='ASC';
    }
    else
    {
        frm.sortCol.value = val.replace('_DESC','');
        frm.ord.value='DESC';
    }
    frm.list_sort_col.value=val;
    frm.submit();
}

/** Sort displaying vehicle list page according to specified arguments. */
function sortListFormByAjax(frm,val, extraAction)
{
    if(val.match(/_ASC/i))
    {
        frm.sortCol.value = val.replace('_ASC','');
        frm.ord.value='ASC';
    }
    else
    {
        frm.sortCol.value = val.replace('_DESC','');
        frm.ord.value='DESC';
    }
    frm.list_sort_col.value=val;

    if(extraAction)
        eval(extraAction);
}

/**To popup message while removing single records */
function confirmDel(ref)
{
    if(confirm(msgDeleteConfirm))
        window.location.replace(ref);
}

function confirmDelJQNL(url,sCode)
{
    if(confirm(msgDeleteConfirm))
    {
        jQuery.post(url,'',function(data){

            if(_isNLSite == 1)
                notificationBox(data);
            else
            {
                jQuery('#message').addClass('inline_msg mt10');
                jQuery('#message').html(data);
                var para = '&site='+sCode;
            }

            jQuery.post('listFindAgent.php?ajx=1',para,function(data){

                responseArr=data.split('@@$#$@@');

                jQuery('#more_list').html(responseArr[0]);
                jQuery('#count_fa').html(responseArr[1]);
            });
        });
    }
}

/**To popup message while removing multiple records*/
function confirmMultiDel(act,frm)
{
    if(confirm(msgDeleteConfirm))
    {
        if (act != '')
            eval("document."+frm+".action="+'act');

        eval("document."+frm+".submit()");
    }
}

/** Function to swap image (used in Map etc.)*/
function swapImage(imgname,path,adId,imageid)
{
    adId.value=imageid;
    imgname.src=path;
}

/** Function to swap image For Compare modal Box*/
function swapCompareImage(imgname,path,adId,imageid)
{
    /**
     * @NOTE : This condition is for IE6 and IE7
     * FF considers the two same imagename object as NodeList so we can access it through Array
     * While IE6 and IE7 will Overwrite New Same object with Old one, so imagename will return last(New) Object in DOM
     */
    if(imgname[1]) imgname=imgname[1];

    /** This adId is of another form generated through AJAX Response */
    try{
    adId.value=imageid;
    }
    catch(e){}

    imgname.src=path;
}

/**Function to change full image of VIF etc.*/
function loadImage(newimg,img_width,lImg_idNo,tot_image,commonImageUrl)
{
    document.getElementById('fullimg').src=newimg;

    if(tot_image > 0)
    {
        for(j=1; j<=tot_image; j++)
        {
            if(document.getElementById('zoom_'+j))
            {
                document.getElementById('zoom_'+j).innerHTML='';
                document.getElementById('zoom_image_icon').style.display='block';
            }
        }

        if(document.getElementById('video_icon_id'))
            document.getElementById('video_icon_id').style.display='block';
        if(document.getElementById('zoom_'+lImg_idNo))
        {
            if(_isNLSite == 1)
                document.getElementById('zoom_'+lImg_idNo).innerHTML='<img style="cursor:pointer;" class="img png" src="'+commonImageUrl+'/zoom_modal_iconNL.gif" width="40" height="40" alt="'+capLargeImgIcon+'" title="'+capLargeImgIcon+'"/>';
            else
                document.getElementById('zoom_'+lImg_idNo).innerHTML='<img style="cursor:pointer;" class="img png" src="'+commonImageUrl+'/zoom_modal_icon.png" width="24" height="24" alt="'+capLargeImgIcon+'" title="'+capLargeImgIcon+'"/>';
        }
    }
    if(img_width)
    {
        document.getElementById('zoom_image_icon').style.width=img_width+'px';
        if(document.getElementById('video_icon_id'))
          document.getElementById('video_icon_id').style.width=img_width+'px';
    }
}
/** function which checks the value which is only number*/
function updateNumField(o)
{
    var t=frmCheckUInt(o.value);
    if (t)
        frmD[o.name]=o.value;
    else
        o.value=(frmD[o.name]!=null?frmD[o.name]:'');

    return t;
    o.focus();
}
var frmD=new Object();

function frmCheckUInt(o)
{
    for (var i=0;i < o.length;i++)
    {
        var c=o.charAt(i);
        if (c < '0' || c >'9')
        return false;
    }
    return true;
}
/** Function to show the share bubble modal in ad information page. */
function shareModal(opt,e,id_ad,page_title)
{
    page_title=page_title.replace('(',' - ');
    page_title=page_title.replace(')','');

    /** For getting the height of the page */
    var yScroll;

    /** Finds the full height of web-page(i.e. From start(top) to end(bottom)) */
    if (window.innerHeight && window.scrollMaxY) {
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ /** all but Explorer Mac */
        yScroll = document.body.scrollHeight;
    } else { /** Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari */
        yScroll = document.body.offsetHeight;
    }

    var windowHeight;

    /** Finds the height of viewable part of screen */
    if (self.innerHeight) { /** all except Explorer */
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { /** Explorer 6 Strict Mode */
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { /** other Explorers */
        windowHeight = document.body.clientHeight;
    }

    /** for small pages with total height less then height of the viewport */
    if(yScroll < windowHeight)
        pageHeight=windowHeight;
    else
        pageHeight=yScroll;

    /** IF the "share" option clicked from VIF page */
    if(opt == 'S' || opt == 'SDS')
    {
        var musY, setScroll;

        if(opt == 'S')
        {
            pageURL=location.protocol+'//'+location.hostname+'/vifBubbleShare.php?page_title='+page_title+'&id_ad='+id_ad;
            $('lightbox').style.left='41%';
        }
        if(opt == 'SDS')
        {
            pageURL=location.protocol+'//'+location.hostname+'/vifBubbleShare.php?page_title='+page_title+'&id_ad='+id_ad;
            $('lightbox').style.left='65%';
        }

        musY = getMouseY(e);  /** Gives Y-coordinate(position) of mouse-click and works for all browsers. */

        /** setScroll - Sets the position of share-bubble near the share link */
        if(browser == 'Internet Explorer')
        {
            setScroll=musY-450;
            $('lightbox').style.top=musY+'px';
        }
        else
        {
            setScroll=musY-400;
            $('lightbox').style.top=musY+'px';
        }

        $('lightbox').style.width='430px';
        lightbox.prototype.content=pageURL;
        lightbox.prototype.activate(setScroll,pageHeight);
    }
}
/** fucntion to refreshSession while posting Ad */
function refreshSession()
{
    var http = false;
    if(navigator.appName == "Microsoft Internet Explorer")
        http = new ActiveXObject("Microsoft.XMLHTTP");
    else
        http = new XMLHttpRequest();

    http.open('GET',location.protocol+'//'+location.hostname+'/refreshSession.php');
    http.setRequestHeader("Content-Type", "text/html;charset=UTF-8");
    http.onreadystatechange=function()
    {
        if(http.readyState == 4) { }
    }
    http.send(null);
    return false;
}

/** Standard string replace functionality */
function str_replace(haystack, needle, replacement)
{
    var temp = haystack.split(needle);
    return temp.join(replacement);
}

function splchar_replace(find, replace, str)
{
    var ra = replace instanceof Array, sa = str instanceof Array, l = (find = [].concat(find)).length, replace = [].concat(replace), i = (str = [].concat(str)).length;
    while(j = 0, i--)
        while(str[i] = str[i].split(find[j]).join(ra ? replace[j] || "" : replace[0]), ++j < l);
    return sa ? str : str[0];
}

function preg_replace(pattern, replaceTo, str)
{
    for(i=0; pattern.length>=i;i++)
    {
        var regex = new RegExp(pattern[i],"g");
        str = str.replace(regex,replaceTo[i]);
    }
    return str;
}

function createNIDForm(idUser)
{
    var strIdUser='strIdUser='+idUser;
    var xmlHttpReq=createXMLHttpObject();
    var returnUrl=str_replace(location.href,'&','@');

    xmlHttpReq.open('GET',location.protocol+'//'+location.hostname+'/createNIDForm.php?'+strIdUser+'&returnUrl='+returnUrl);
    xmlHttpReq.setRequestHeader("Content-Type", "text/xml;charset=UTF-8");
    xmlHttpReq.onreadystatechange=function()
    {
        if(xmlHttpReq.readyState == 4)
        {
            document.getElementById('nidReqUser').innerHTML='';
            document.getElementById('nidReqUser').innerHTML=xmlHttpReq.responseText;
            document.listNorthId.submit();
        }
    }
    xmlHttpReq.send(null);
    return false;
}

/** Function to check characters length of word but not check url  */
function isMaxWord(txtVal,sep,len)
{
    if (txtVal == '')
        return true;
    else
    {
        if(sep ==  ' ')
            tempValue=txtVal.split(/\s+/);
        else
            tempValue=txtVal.split(sep);

        for(var i=0; i < tempValue.length; i++)
        {
            var lnkUrl=/^(http:|www\.).*$/;
            if(tempValue[i].search(lnkUrl)==-1 && tempValue[i].length > len)
            {
                return 0;
                break;
            }
        }
    }
}

/** This function check for word length in the string entered in the given textbox(input field) */
function txtValid(theTxtbox,maxWordLen)
{
    if(isLong(theTxtbox.value," ",maxWordLen) == 0)
    {
        alert(msgLngWordFPart + maxWordLen + msgLngWordSPart);
        theTxtbox.focus();
        return false;
    }
    else
        return true;
}

/** This function is return whole url with append of selected search criteria*/
function cleanFrmUrl(qs)
{
    var l =qs.elements.length;
    var u='';

    u=u.replace(/\s/g,'-').toLowerCase();

    for(var i = 0; i < l; i++)
    {
        var e=qs.elements[i];

        if(e.name == 'search' || e.name == 'qsm')
           continue;

        if(e.type == 'select-multiple')
        {
            var si=new Array();
            var count=0;
            var k;
            while (e.selectedIndex != -1)
            {
                if (e.selectedIndex != 0)
                {
                    u=u+e.name+'='+e.options[e.selectedIndex].value+'&';
                    si[count++]=e.selectedIndex;
                }
                e.options[e.selectedIndex].selected=false;
            }

            for(k=0; k<si.length; k++)
                e.options[si[k]].selected=true;
        }
        else if(((e.type == 'checkbox' || e.type == 'radio') && e.checked && e.value))
        {
            u=u+e.name+'='+e.value+'&';
        }
        else if(e.value && !isblank(e.value) && e.type != 'checkbox' && e.type != 'radio')
        {
            if(e.value.indexOf('#') != -1)
                u=u+e.name+'='+escape(e.value)+'&';
            else
                u=u+e.name+'='+e.value+'&';
        }
    }
    return u.substr(0,u.length-1);
}

/* Function to confirm find agent through ajax */
function ajxConfirmAgent(url)
{
    jQuery.post(url,'',function(data){
        responseArr=data.split('##$$123$$##');

        jQuery('#activeLink'+responseArr[2]).html(responseArr[0]);
        jQuery('#agentLink'+responseArr[2]).html('');

        jQuery('#message_'+responseArr[2]).html(responseArr[1]);
        jQuery('#message_'+responseArr[2]).attr('class','message margin_top1');
        jQuery('#message_'+responseArr[2]).css('block');
    });
    return false;
}


/** Function call from badAdPress() to check the fields. */
function checkBblFld()
{
    if((!document.getElementById('report_ad').checked) && (!document.getElementById('report_owner').checked))
    {
        if(document.getElementById('report_video'))
        {
            if(!document.getElementById('report_video').checked)
            {
                alert(msgMandet);
                return false;
            }
        }
        else
        {
            alert(msgMandet);
            return false;
        }
    }

    if(isblank(document.getElementById('content').value))
    {
        alert(msgMandet);
        document.getElementById('content').focus();
        return false;
    }
    else
    {
        var report=document.getElementById('content').value;

        if(report.length > 300)
        {
            alert(msgLongReport);
            return false;
        }
    }

    if(document.getElementById('user_name'))
    {
     var uname=document.getElementById('user_name').value;

     if((!isblank(uname)) && (!checkFullName(uname)))
     {
         alert(msgFullFLname);
         document.getElementById('user_name').focus();
         return false;
     }
    }

    if(document.getElementById('user_email'))
    {
     var umail=document.getElementById('user_email').value;

     if((!isblank(umail)) && (!emailInvalid(umail)))
     {
         alert(msgInvalidEmail);
         document.getElementById('user_email').focus();
         return false;
     }
    }

    return true;
}

/** Function to count hit count for bouns logo. */
function bonus_counter(id_bonus,siteCode,s_URL)
{
    var xmlHttpReq=createXMLHttpObject();

    xmlHttpReq.open('GET',s_URL+'/updateBounusCount.php?id_bonus='+id_bonus+'&s_code='+siteCode);
    xmlHttpReq.setRequestHeader("Content-Type", "text/html;charset=UTF-8");
    xmlHttpReq.onreadystatechange=function()
    {
        if(xmlHttpReq.readyState == 4) { }
    }
    xmlHttpReq.send(null);
    return false;
}

/** To check talknow phone number validation */
function chkTNPhone()
{
    if(isblank(document.getElementById('tn_phoneNumber').value) || !check(document.getElementById('tn_phoneNumber').value)){
        alert(msgPhoneFormat);
        document.getElementById('tn_phoneNumber').focus();
        return false;
    }
    else {
        callRequestData();
    }
}

/** function to show/hide AdType in Posting page*/
function showHideAdType(sCode,showAll,hideAll)
{
    var arrSiteCode=new Array('NA','NM','NT','NP','NV','NC','NF','NH','NK');

    for(i=0;i<arrSiteCode.length;i++)
    {
        if(sCode != arrSiteCode[i])
        {
            var hideAdType=document.getElementById('adType_'+arrSiteCode[i]);
            hideAdType.style.display='none';
            document.getElementById('showHideCap_'+arrSiteCode[i]).innerHTML= showAll;
            document.getElementById('showHideCap_'+arrSiteCode[i]).className='arrow_open_postad';
        }
    }
    var dispAdType=document.getElementById('adType_'+sCode);

    if(dispAdType.style.display == 'none')
    {
        dispAdType.style.display='block';
        document.getElementById('showHideCap_'+sCode).innerHTML=hideAll;
        document.getElementById('showHideCap_'+sCode).className='arrow_hide_postad';
    }
    else
    {
        dispAdType.style.display='none';
        document.getElementById('showHideCap_'+sCode).innerHTML=showAll;
        document.getElementById('showHideCap_'+sCode).className='arrow_open_postad';
    }
}

/** Function to Clean URL */
function cleanRewriteUrl(str)
{
    var rExps=[{re:/[\xC0-\xC6]/gi, ch:'A'},{re:/[\xE0-\xE6]/gi, ch:'a'},{re:/[\xC8-\xCB]/gi, ch:'E'},{re:/[\xE8-\xEB]/gi, ch:'e'},{re:/[\xCC-\xCF]/gi, ch:'I'},{re:/[\xEC-\xEF]/gi, ch:'i'},{re:/[\xD2-\xD6]/gi, ch:'O'},{re:/[\xF2-\xF6]/gi, ch:'o'},{re:/[\xD9-\xDC]/gi, ch:'U'},{re:/[\xF9-\xFC]/gi, ch:'u'},{re:/[\xD1]/gi, ch:'N'},{re:/[\xF1]/gi, ch:'n'},{re:/[^a-zA-Z0-9\/_|+ -]/gi, ch:''},{re:/[\/_| -]+/gi, ch:'-'}];

    for(var i=0, len=rExps.length; i<len; i++)
        str=str.replace(rExps[i].re, rExps[i].ch);

    return str.toLowerCase();
}

function clickCounter(identifier)
{
    img = document.createElement('img');
    img.src = 'http://www.nettiauto.com/br.gif?'+identifier;
    document.documentElement.appendChild(img);
    return true;
}

function showHideEntity(divId,classId)
{
    if(document.getElementById(divId).style.display == 'none')
        document.getElementById(divId).style.display='block';
    else
        document.getElementById(divId).style.display='none';

    if(classId != '')
    {
        if (_isNLSite == 1)
         {
             if(document.getElementById(classId).className == 'search_hist_open')
                 document.getElementById(classId).className='search_hist_hide';
             else
                 document.getElementById(classId).className='search_hist_open';
         }
         else
         {
             if(document.getElementById(classId).className == 'arrow_open')
                 document.getElementById(classId).className='arrow_hide';
             else
                 document.getElementById(classId).className='arrow_open';
         }
    }
}

function delcookie(cookiNm)
{
    var cookiNm;
    document.cookie = cookiNm+'=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/;';
}

/** Get the cookie value */
function GetCookie(name)
{
    var result=null;
    var myCookie = " " + document.cookie + ";";
    var searchName = " " + name + "=";
    var startOfCookie = myCookie.indexOf(searchName);
    var endOfCookie;
    if (startOfCookie != -1)
    {
        startOfCookie += searchName.length;
        /** skip past cookie name */
        endOfCookie = myCookie.indexOf(";", startOfCookie);
        result = unescape(myCookie.substring(startOfCookie,endOfCookie));
    }
    return result;
}

function showHideSaveVIF(divIdFirst,divIdSec)
{
    if(document.getElementById(divIdFirst).style.display == 'block')
    {
        document.getElementById(divIdFirst).style.display='none';
        document.getElementById(divIdSec).style.display='block';
    }
}

function cookSaveVIF(min,expand,siteCode)
{
    var cookVal;

    cookVal=GetCookie('__shVIF'+siteCode);

    if(cookVal == 'H')
        cookVal='S';
    else
        cookVal='H';

    /** IF the browser is IE6, Just show/Hide box */
    if(navigator.appVersion.indexOf('MSIE 6.0') != -1) // IE-6
    {
        if(document.getElementById('vehicle_window').style.display == 'block')
        {
            document.getElementById('vehicle_window').style.display='none';
            if (_isNLSite == 1)
                document.getElementById('showHideImg').className='vif_arrow_open';
            else
                document.getElementById('showHideImg').className='minus_icon';
            document.getElementById('showHideImg').title=expand;
        }
        else
        {
            document.getElementById('vehicle_window').style.display='block';
            if (_isNLSite == 1)
                document.getElementById('showHideImg').className='vif_arrow_close';
            else
                document.getElementById('showHideImg').className='plus_icon';
            document.getElementById('showHideImg').title=min;
        }
    }
    else    /** show/Hide the box according to cookie. */
    {
        if(cookVal == 'S')
        {
            document.getElementById('vehicle_window').style.display='block';
            if (_isNLSite == 1)
                document.getElementById('showHideImg').className='vif_arrow_open';
            else
                document.getElementById('showHideImg').className='minus_icon';
            document.getElementById('showHideImg').title=min;
        }
        else if(cookVal == 'H')
        {
            document.getElementById('vehicle_window').style.display='none';
            if (_isNLSite == 1)
                document.getElementById('showHideImg').className='vif_arrow_close';
            else
                document.getElementById('showHideImg').className='plus_icon';
            document.getElementById('showHideImg').title=expand;
        }
    }

    document.cookie = '__shVIF'+siteCode+'=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/;';

    var date = new Date();
    date.setTime(date.getTime()+(31536000*9999));
    document.cookie = '__shVIF'+siteCode+'='+cookVal+'; expires='+ date.toGMTString() + '; path=/;';
}

function createXMLHttpObject()
{
    try { return new XMLHttpRequest(); } catch(e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}

    /** no XHR support */
    return null;
}

/** Called from posting from 'back to attach image' part */
function callAddVehicle(mlink)
{
    var searchStr=mlink.search("id_item");

    /** Will evaluate this condition in case of NF and KP*/
    if(searchStr != -1)
    {
        var eleValue='';

        if(document.getElementById('sel_ad_type'))
            eleValue=document.getElementById('sel_ad_type');
        else
            eleValue=document.attachimg.ad_type;

        if(eleValue.value == 'S')
        {
            alert(msgSelectAdType);
            return false;
        }
    }

    document.attachimg.action=mlink;
    document.attachimg.submit();
    return false;
}

/** Called from post Ad phase 1 from Go Button part */
function callFromPostAdNL(radioObj)
{
    var radioLength=radioObj.length;
    for(var i = 0; i < radioLength; i++) {
        if(radioObj[i].checked) {
            document.postAd.action=radioObj[i].value;
        }
    }
    document.postAd.submit();
    return false;
}

function addSelTown(t,st) {

    var addTown=true;

    townTxt=t.options[t.selectedIndex].text;
    townVal=t.options[t.selectedIndex].value;

    if(townVal == '' || townVal == '0')
        addTown=false;
    else
    {
        if(st.length == 1 && st.options[0].value == '')
            st.length--;

        domTxt = idiv((t.name == 'id_town_bubble') ? 'lastDomicileBubble' : 'lastDomicile').value;

        var tot=st.length;
        if(tot > 0)
        {
            for(o=0; o < tot; o++)
            {
                var tmpValue=st.options[o].value;
                var tmpText=st.options[o].text;

                if(townVal == tmpValue)
                {
                    addTown=false;
                    break;
                }
                else if(tmpValue.match(/@/))
                {
                    arrTown=tmpValue.split('@');

                    arrSelectedTown=arrTown[0].split('-');
                    for(var i=0;i < arrSelectedTown.length;i++)
                    {
                        if(arrSelectedTown[i] == townVal)
                        {
                            if(t.name == 'id_town_bubble')
                            {
                                el = idiv('selected_town_list_'+tmpValue);
                                el.parentNode.removeChild(el);
                            }
                            st.remove(o);
                            addTown=true;
                        }
                    }
                }
                else if(townVal.match(/@/))
                {
                    arrTown=townVal.split('@');
                    arrSelectedTown=arrTown[0].split('-');

                    for(var i=0;i < arrSelectedTown.length;i++)
                    {
                        for(var j=0;j<tot;j++)
                        {
                            if(arrSelectedTown[i] == st[j].value)
                            {
                                if(t.name == 'id_town_bubble')
                                {
                                    el = idiv('selected_town_list_'+arrSelectedTown[i]);
                                    el.parentNode.removeChild(el);
                                }
                                st.remove(j);
                                tot--;
                                addTown=true;
                            }
                        }
                    }
                }
                else if(tmpValue.match(/d/))
                {
                    allTown=tmpValue.replace('d','');

                    if(t.name == 'id_town_bubble')
                    {
                        arrSelectedDom=tmpText.split(' - ');
                        arrTownTxt=townTxt.split(' - ');
                    }
                    else
                    {
                        arrSelectedDom=tmpText.split(' -');
                        arrTownTxt=townTxt.split(' -');
                    }

                    if(arrSelectedDom[0] == domTxt)
                    {
                        if(t.name == 'id_town_bubble')
                        {
                            el = idiv('selected_town_list_'+tmpValue);
                            el.parentNode.removeChild(el);
                        }
                        st.remove(o);
                        addTown=true;
                    }
                }
                else if(townVal.match(/d/))
                {
                    arrTown=townVal.replace('d','');

                    if(t.name == 'id_town_bubble')
                    {
                        arrSelectedDom=tmpText.split(' - ');
                        arrTownTxt=townTxt.split(' - ');
                    }
                    else
                    {
                        arrSelectedDom=tmpText.split(' -');
                        arrTownTxt=townTxt.split(' -');
                    }

                    if(arrSelectedDom[0] == domTxt && (arrTownTxt[0]=='Kaikki' || arrTownTxt[0]=='Any'))
                    {
                        if(t.name == 'id_town_bubble')
                        {
                            el = idiv('selected_town_list_'+tmpValue);
                            el.parentNode.removeChild(el);
                        }
                        st.remove(o);
                        tot--;
                        o--;
                        addTown=true;
                    }
                }
            }
        }
    }

    if(addTown)
    {
        if(t.name == 'id_town_bubble')
            optText = domTxt+' - '+townTxt;
        else
            optText = domTxt+' -'+townTxt;

        st.options[st.length] = new Option(optText,townVal);

        if(t.name == 'id_town_bubble' && townVal)
            idiv('selected_town_list').innerHTML += '<li class="qs_town_list" id="'+'selected_town_list_'+townVal+'" value="'+townVal+'" onclick="bblRemoveTown(this);">' + townTxt + ', ' + domTxt + '<span title="' + emptySelection + '">&nbsp;</span>' ,townVal + '</li>';
    }
}

/** Remove element from array by index. */
function removeByIndex(arr, index)
{
    arr.splice(index, 1);
}

/** Remove selected domicile/town value from listing & hidden element's value. */
function bblRemoveTown(list_ele)
{
    /** Get element id for remove element from listing. */
    var strRemove = list_ele.id.replace(/selected_town_list_/,"");

    var prtNode = list_ele.parentNode;
    /** Remove element from listing. */
    list_ele.parentNode.removeChild(list_ele);

    /** String to array */
    bblTownArr = document.srch.selTown.value.split(',');

    /** Search value in array and take index. */
    //var indexRemove = bblTownArr.indexOf(strRemove);
    var indexRemove = jQuery.inArray(strRemove,bblTownArr);

    /** Remove element from array if index found. */
    if(indexRemove != -1)
        removeByIndex(bblTownArr, indexRemove);

    /** Set remaining value from array to selTown element using array to string functionality */
    document.srch.selTown.value = bblTownArr.join();

    if(!document.srch.selTown.value)
        idiv('selected_town_list').style.backgroundColor="";

    callAjax(document.srch);
}

function removeSelTown(v1)
{
    var p=v1.id_sel_town.selectedIndex;
    var j=0;
    var tot=v1.id_sel_town.options.length;

    if(tot > p)
    {
        for(i=p; i<=tot; i++)
        {
            j=i+1;

            if(j > (tot-1))
                j=tot-1;

            var disp=v1.id_sel_town[j].text;
            var val=v1.id_sel_town[j].value;

            selOpt=new Option(disp,val);
            eval("v1.id_sel_town.options[i]=selOpt");
        }
    }
    v1.id_sel_town.length=tot-1;

    /** If no option is there then add "any" as default */
    if(v1.id_sel_town.options.length == 0)
    {
        selOpt=new Option('','');
        eval("v1.id_sel_town.options[0]=selOpt");
    }
}
/** This function call from 'resetForm' function to get the default value of given form field name
    advFormField : This contain the HTMLObject i.e. this.form.fielname
    defValArr : This contain the Global array that set for default value
    txt : optional if no any selected option then display the caption value like ------ Any ------
*/
function getDefValue(advFormField,defValArr,txt)
{
    var strVal=strTxt='';
    if(advFormField)
    {
        /** First Remove all the value of given form field name */
        advFormField.options.length=0;
        selOpt=new Option(txt,'');
        eval("advFormField.options[0]=selOpt");

        if(defValArr.length > 0)
        {
            /** Set/add the default value of given form filed from defArray array */
            for(var i=0; i<defValArr.length; i++)
            {
                /** Split array split_defValArr[0] have value and split_defValArr[1] have text */

                split_defValArr=defValArr[i].split(/\,/);

                for(s=0;s<split_defValArr.length-1;s++)
                    strVal +=split_defValArr[s]+',';

                strVal=strVal.substring(0,strVal.length-1);
                strTxt=split_defValArr[split_defValArr.length-1];

                selOpt=new Option(strTxt,strVal);
                eval("advFormField.options[i]=selOpt");
                strVal='';
            }
        }
    }
}

/** Change text color of search box. */
function colorChange(val)
{
    if(val.value == val.defaultValue)
    {
        val.value='';
        val.style.color = '#000000';
    }
}

function setCookies()
{
    document.cookie = '__invdBrw=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/;';
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+7);
    document.cookie = '__invdBrw=Y; expires='+exdate.toGMTString();+' path=/;';
}

/** Set default value of search box. */
function setDefaultValIfBlank(val)
{
    if(val.value == '')
    {
        val.value=val.defaultValue;
        val.style.color = '#666666';
    }
}

/** Displays category selection box in list owner page if sms type is category. */
function apeShowHideCategory(val,id)
{
    if (val == 'category')
        document.getElementById('showCatOption'+id).style.display='inline';
    else
        document.getElementById('showCatOption'+id).style.display='none';
}

/** Called from owner page which will check for mandatory fields. */
function apeListForm(baseUrl)
{
    var i,flag='N',flagCategory='N';

    var tempLen=FlagAdId.length;
    for (j=0; j < tempLen; j++)
    {
        var tempType=FlagAdId[j];

        if(document.getElementById('arrChk['+tempType+']') && document.getElementById('arrChk['+tempType+']').checked)
        {
            flag='Y';

            if (document.getElementById('arrSmsType['+tempType+']').value == 'category')
            {
                if (document.getElementById('arrCategoryId['+tempType+']').value == '')
                    flagCategory='Y';
            }
        }
    }

    if(flag != 'Y')
    {
        alert(msgSelectAtLeastOneApe);
        return false;
    }
    else if (flagCategory != 'N')
    {
        alert(msgLeastOneCategory);
        return false;
    }
    else
    {
        document.sortl.method='post';
        document.sortl.action=baseUrl+'/payment.php';

        return true;
    }
}

/** Unset cookies when clicked on Cancel button */
function apeCancel(siteCode)
{
   var now = new Date();

    /** Decrease a day */
    now.setDate(now.getDate() - 1);

    document.cookie=siteCode+'_SMS_APID=; '+now+'; path=/;';
    document.cookie=siteCode+'_SMS_MAXSMS=; '+now+'; path=/;';
    document.cookie=siteCode+'_SMS_SMSTYPE=; '+now+'; path=/;';
    document.cookie=siteCode+'_SMS_CATEGORY=; '+now+'; path=/;';
    document.cookie=siteCode+'_SMS_REDIRECT=; '+now+'; path=/;';

    var ru = document.getElementById('ape_redirectPath').value;
    window.location.href=ru.replace('autoload=true', '');

    return true;
}

/** Get Page scroll Offset for APE */
function getScroll()
{
    var yScroll;

    if (typeof(window.pageYOffset) == 'number')
        yScroll = window.pageYOffset;
    else if (document.body && document.body.scrollTop)
        yScroll = document.body.scrollTop;
    else if (document.documentElement && document.documentElement.scrollTop)
        yScroll = document.documentElement.scrollTop;
    else
        yScroll = 0;

    return yScroll;
}

/** jQuery Function Starts here **/
/** Called from lang file which will be called on click of 'Click here' link in sms window. */
function apePaymentModalJQ(smsType,redirectUrl,catId)
{
    window.onerror = noError;
    pageURL=baseUrl+'/paymentModal.php?smsType='+smsType;
    if(catId)
        pageURL=pageURL+'&catId='+catId;
    if(redirectUrl)
        pageURL=pageURL+'&redirectUrl='+redirectUrl;

     jQuery.fn.colorbox({
        href:pageURL,onComplete:function(){jQuery('#adId').focus();}
     });
     return false;
}
function noError(){return true;}
/** Called from modal template which will be called on submit from modal box. */
function apeModalFormJQ(frmObj)
{
    var apid=frmObj.adId;

    if(isblank(apid.value))
    {
        apid.focus();
        alert(msgMandet);
        return false;
    }
    else
    {
        var chkValidityPage=baseUrl+'/checkAdIdValidity.php?ajxLogin=1';
        var pars=jQuery(frmObj).serialize();
        jQuery.post(chkValidityPage+((chkValidityPage.indexOf('?') > 0) ? '&' : '?'),pars,function(data){
            if (data!='')
            {
                idiv('msgApeError').innerHTML='<table width="100%" border="0" cellspacing="3" cellpadding="0"><tr><td height="27" class="message">'+data+'</td></tr></table>';
                return false;
            }
            else
            {
                frmObj.method='post';
                frmObj.action='/payment.php';
                frmObj.submit();
                return true;
            }

        });
        return false;
    }
    return false;
}

/** Called from modal template which will be called on submit from modal box. */
function apeModalFormJQNL(frmObj)
{
    var apid=frmObj.adId;

    if(isblank(apid.value))
    {
        apid.focus();
        alert(msgMandet);
        return false;
    }
    else
    {
        var chkValidityPage=baseUrl+'/checkAdIdValidity.php?ajxLogin=1';
        var pars=jQuery(frmObj).serialize();
        jQuery.post(chkValidityPage+((chkValidityPage.indexOf('?') > 0) ? '&' : '?'),pars,function(data){
            if (data!='')
            {
                idiv('msgApeError').innerHTML='<table width="100%" border="0" cellspacing="3" cellpadding="0"><tr><td height="27" class="inline_msg">'+data+'</td></tr></table>';
                return false;
            }
            else
            {
                frmObj.method='post';
                frmObj.action='/payment.php';
                frmObj.submit();
                return true;
            }

        });
        return false;
    }
    return false;
}
function display_searchJQ()
{
    jQuery('#adv_option').toggle();
}

/** SAVEVIF: Internal variables */
var currSlide = 1;
var nxtSlide = 0;
var working = false;
var mvBk='N';
var slideWidth;

/** SAVEVIF: Tranition to the next slide */
function saveVIFSlide(nxtSlide,mvBk,slideWidth)
{
    /** Make sure previous transition is complete before proceeding. */
    if (!working)
    {
        working = true;

        var slides = jQuery('div .slideContainer');

        /** Slide transtion */
        if(mvBk == 'N')
        {
            if(jQuery('#slide'+currSlide) != null)
            {
                jQuery('#slide'+currSlide).css({left:'0px',top:'0px',display:'inline',zIndex:'2'});
                jQuery('#slide'+nxtSlide).css({left:slideWidth+'px',top:'0px',display:'inline',zIndex:'1'});
                jQuery('#slide'+currSlide).animate({left:'-'+slideWidth+'px'}, "slow");
                jQuery('#slide'+nxtSlide).animate({left:'0px'}, "slow",function(){working = false;});
            }
        }
        else
        {

                jQuery('#slide'+currSlide).css({left:'0px',top:'0px',display:'inline',zIndex:'2'});
                jQuery('#slide'+nxtSlide).css({left:'-'+slideWidth+'px',top:'0px',display:'inline',zIndex:'1'});
                jQuery('#slide'+currSlide).animate({left:'+'+slideWidth+'px'}, "slow");
                jQuery('#slide'+nxtSlide).animate({left:'0px'}, "slow",function(){working = false;});

        }
        working = false;

        var vif_pageing='';
        jQuery('#slideshowNavigation').html('');
        if(slides.length > 1)
        {
            /** When click on Last slide(no) */
            if(nxtSlide != 1)   // Slide Move back
                vif_pageing += '<a href="javascript:saveVIFSlide('+(nxtSlide-1)+',\'Y\','+slideWidth+');" class="small_text">&#171; '+msgPrev+'</a> &nbsp;';

            for(var s=1; s <= slides.length; s++)
            {
                if(nxtSlide == s)
                    vif_pageing += '<span class="small_text">'+s+'</span>' +' &nbsp;';
                else
                {
                    if(s > nxtSlide)
                        vif_pageing += '<a href="javascript:saveVIFSlide('+s+',\'N\','+slideWidth+');" class="small_text">' + s +'</a> &nbsp;';
                    else    // Slide Move back
                        vif_pageing += '<a href="javascript:saveVIFSlide('+s+',\'Y\','+slideWidth+');" class="small_text">' + s +'</a> &nbsp;';
                }
            }

            /** When click on First slide(no) */
            if(slides.length != nxtSlide)
                vif_pageing += '<a href="javascript:saveVIFSlide('+(nxtSlide+1)+',\'N\','+slideWidth+');" class="small_text">'+msgNext+' &#187;</a> &nbsp;';

            jQuery('#slideshowNavigation').html(vif_pageing);
        }
        currSlide=nxtSlide;
    }
}

function AjaxDeleteJQ(anchorObj,event)
{
    var arrUrl=anchorObj.href.split("?");
    var pars="ajxDelstr=1&"+jQuery(document.frmqueans).serialize()+"&"+arrUrl[1];
    if(confirm(msgDeleteConfirm))
    {
        var pars="ajxDelstr=1&"+jQuery(document.frmqueans).serialize()+"&"+arrUrl[1];
        jQuery.get(arrUrl[0],pars,function(data){
            document.getElementById('submitXQA').innerHTML=data;
        });

        return false;
    }
    return false
}
function dispMoreSrchOpt(idDiv)
{
   jQuery('#'+idDiv).toggle();
}

/** Function to create nid info bubble */
function nidCreationInfoJQ()
{
    pageURL = location.protocol+'//'+location.hostname+'/northIdInfo.php?mainOnly=1';
    jQuery.fn.colorbox({
        href:pageURL
     });
}

/* Function to confirm find agent through ajax */
function ajxConfirmAgentNLJQ(url)
{
    jQuery.post(url,'',function(data){
        responseArr=data.split('##$$123$$##');

        jQuery('#activeLink'+responseArr[2]).html(responseArr[0]);
        jQuery('#agentLink'+responseArr[2]).html('');

        jQuery('#message_'+responseArr[2]).html(responseArr[1]);
        jQuery('#message_'+responseArr[2]).attr('class','inline_msg mt10');
        jQuery('#message_'+responseArr[2]).css('block');
        jQuery('#status_cls_'+responseArr[2]).removeClass('active_grey');
        jQuery('#status_cls_'+responseArr[2]).addClass('active_green');
    });
    return false;
}

// function to disable search agent
function ajxChangeAgentStatusNLJQ(url)
{
    jQuery.post(url,'',function(data){
        responseArr=data.split('##$$123$$##');

        if(_isNLSite == 1)
            notificationBox(responseArr[0]);
        else
        {
            jQuery('#message_'+responseArr[1]).html(responseArr[0]);
            jQuery('#message_'+responseArr[1]).attr('class','inline_msg mt10');
        }
        jQuery('#message_'+responseArr[1]).css('block');

        if(responseArr[2] == 1)
        {
            jQuery('#status_cls_'+responseArr[1]).removeClass('active_grey');
            jQuery('#status_cls_'+responseArr[1]).addClass('active_green');
            jQuery('#agent_status_'+responseArr[1]).checked=true;
        }
        else
        {
            jQuery('#status_cls_'+responseArr[1]).removeClass('active_green');
            jQuery('#status_cls_'+responseArr[1]).addClass('active_grey');
            jQuery('#agent_status_'+responseArr[1]).checked=false;
        }
    });
    return false;
}

/** Calculates price on owner page */
function apeCalTotPrice(resetY, siteCode)
{
    var tempLen=FlagAdId.length;
    var price = maxSms = finalPrice = 0;

    for (j=0; j < tempLen; j++)
    {
        var tempType=FlagAdId[j];

        if(document.getElementById('arrChk['+tempType+']') && document.getElementById('arrChk['+tempType+']').checked && !resetY)
        {
            if(document.getElementById('arrSmsType['+tempType+']').value == 'home' || document.getElementById('arrSmsType['+tempType+']').value == 'make')
            {
                price = 3.0;
                if(siteCode == 'KP' || siteCode == 'EL')
                    price = 1.90;
            }
            else if(document.getElementById('arrSmsType['+tempType+']').value == 'category')
            {
                price = 1.90;
                if(siteCode == 'NA')
                    price = 3.0;
            }

            maxSms = document.getElementById('arrMaxSms['+tempType+']').value;
            finalPrice = finalPrice + (price * maxSms);
        }

        if(resetY == 'Y' && document.getElementById('arrChk['+tempType+']'))
        {
            if(document.getElementById('showCatOption'+tempType).style.display == 'inline')
                document.getElementById('showCatOption'+tempType).style.display='none';

            break;
        }
    }

    idiv('totApePrice').innerHTML=finalPrice.toPrecision(3)+'e';
}

//Function to check blank form in modal-box
function modalBirthYearForm(frmObj)
{
    if(frmObj.birth_year.value == '')
    {
        alert(msgMandet);
        return false;
    }
}
function loadDefBlurService(v1)
{
    if(v1.name=='free_text')
    {
        if(!v1.value)
        {
            v1.value=keywordtext;
            v1.style.color = '#666666';
        }
    }
}
function loadDefBlurServiceNL(v1)
{
    if(v1.name=='free_text')
    {
        if(!v1.value)
        {
            jQuery('#'+v1.id).val(keywordtext_nl);
            jQuery('#'+v1.id).addClass('gray_text');
        }
    }
}
function loadDefBlurDealerLocNL(v1)
{
    if(v1.name=='dealer_location')
    {
        if(!v1.value)
        {
            jQuery('#'+v1.id).val(dealerText_nl);
            jQuery('#'+v1.id).addClass('gray_text');
        }
    }
}
function loadDefBlurDealerKeyNL(v1)
{
    if(v1.name=='search_dealer')
    {
        if(!v1.value)
        {
            jQuery('#'+v1.id).val(dealerKeyText_nl);
            jQuery('#'+v1.id).addClass('gray_text');
        }
    }
}
function loadDefBlurLocationNL(v1)
{
    if(v1.name=='service_location')
    {
        if(!v1.value)
        {
            jQuery('#'+v1.id).val(ziptext_nl);
            jQuery('#'+v1.id).addClass('gray_text');
        }
    }
}
function loadDefClickService(v1)
{
    if(v1.name=='free_text')
    {
        if(v1.value == keywordtext)
        {
            v1.value='';
            v1.style.color = '#3c3c3c';
        }
    }
}
function loadDefClickServiceNL(v1)
{
    if(v1.name=='free_text')
    {
        if(v1.value == keywordtext_nl)
        {
            jQuery('#'+v1.id).val('');
            jQuery('#'+v1.id).removeClass('gray_text');
            jQuery('#'+v1.id).addClass('black_text');
        }
    }
}
function loadDefClickDealerLocNL(v1)
{
    if(v1.name=='free_text')
    {
        if(v1.value == keywordText_nl)
        {
            jQuery('#'+v1.id).val('');
            jQuery('#'+v1.id).removeClass('gray_text');
            jQuery('#'+v1.id).addClass('black_text');
        }
    }
}
function loadDefClickDealerKeyNL(v1)
{
    if(v1.name=='search_dealer')
    {
        if(v1.value == dealerKeyText_nl)
        {
            jQuery('#'+v1.id).val('');
            jQuery('#'+v1.id).removeClass('gray_text');
            jQuery('#'+v1.id).addClass('black_text');
        }
    }
}
function loadDefClickLocationNL(v1)
{
    if(v1.name=='service_location')
    {
        if(v1.value == ziptext_nl)
        {
            jQuery('#'+v1.id).val('');
            jQuery('#'+v1.id).removeClass('gray_text');
            jQuery('#'+v1.id).addClass('black_text');
        }
    }
}

function loadDefClickDealerLocationNL(v1)
{
    if(v1.name=='dealer_location')
    {
        if(v1.value == dealerText_nl)
        {
            jQuery('#'+v1.id).val('');
            jQuery('#'+v1.id).removeClass('gray_text');
            jQuery('#'+v1.id).addClass('black_text');
        }
    }
}

function serviceCatList(url)
{
    jQuery.get(url,'',function(data){
        showResponse(data);
    });
}

function showHideShareAd()
{
    if(document.getElementById('badAd_vif') && document.getElementById('badAd_vif').style.display == 'block')
        document.getElementById('badAd_vif').style.display = 'none';

    if(document.getElementById('share_ad').style.display == 'none')
    {
        document.getElementById('share_ad').style.display = 'block';
        document.getElementById('url_xcng_link').select();
    }
    else
    {
        document.getElementById('share_ad').style.display = 'none';
    }
}

//When answer is submitted from VIF page
function checkQue(file)
{
    var flag='N';

    for(var i=0; i < file.elements.length; i++)
    {
        if(file.elements[i].type == 'text')
        {
            if(!isblank(file.elements[i].value))
            {
                if(!isLong(file.elements[i].value,' ',40))
                {
                    alert(msgTooLongWord);
                    file.elements[i].select();
                    file.elements[i].focus();
                    return false;
                }

                flag='Y';
            }
        }
    }

    if(flag == 'N')
    {
        alert(msgBlankForm);
        return false;
    }
}

function ajaxPriceHistoryJQ(value,containerName,site)
{
    jQuery.post(baseUrl+'/showPriceHistory.php','id_ad='+value+'&site='+site,function(data){
        jQuery('#'+containerName).html(data);
    });
    displayBubble(containerName,'event',1);

    return false;
}

/** Kept in separate files, due to JQuery/Prototype JS */
function ajaxFBuserValidate(frmObj)
{
    var loadingImg = 'loadingImg_fbconnect';
    jQuery('#'+loadingImg).show();
    var pars=jQuery(frmObj).serialize();
    jQuery.post(_su+'/ajaxFBuserValidation.php',pars,function(data){
    if(data == 'S')
    {
        jQuery('#colorbox').css('padding-right','0px');
        jQuery.fn.colorbox({
            href:_su+"/confirmFBConnect.php?mainOnly=1",width:"80%",height:"50%"
        });

        if (jQuery('#'+loadingImg).length != 0)
            jQuery('#'+loadingImg).hide();
    }
    else
    {
       window.location.href=_su+"/addUser.php?fbUsrErr="+data
    }});
    return false;
}

//New Layout common function start From Here
function onFocusUnameJQ(eleId,fldVal)
{
    jQuery('#'+eleId).addClass('black_text2');
    if(jQuery('#'+eleId).val() == fldVal)jQuery('#'+eleId).val("");
}
function onBlurUnameJQ(eleId,fldVal)
{
    if(jQuery('#'+eleId).val() == '')
        jQuery('#'+eleId).removeClass('black_text2');

    if(jQuery('#'+eleId).val() == '')jQuery('#'+eleId).val(fldVal);
}
function onFocusPassHintJQ(eleId,dispId)
{
    jQuery('#'+eleId).hide();
    jQuery('#'+dispId).show();
    jQuery('#'+dispId).focus();
    jQuery('#'+dispId).addClass('black_text2');
}
function removePassImg()
{
    jQuery('#passwd').removeClass('password_img_'+sln);
}
function showPassImg()
{
    if(jQuery('#passwd').val() == '')
        jQuery('#passwd').addClass('password_img_'+sln);
}
function removeUserNameImg()
{
    jQuery('#loginid').removeClass('usrname_img_'+sln);
}
function showUserNameImg()
{
    if(jQuery('#loginid').val() == '')
        jQuery('#loginid').addClass('usrname_img_'+sln);
}

function onFocusPassJQ(eleId,fldVal)
{
    if(jQuery('#'+eleId).val() == fldVal)jQuery('#'+eleId).val("");
}
function onBlurPassJQ(eleId,dispId)
{
    if(jQuery('#'+eleId).val() == '')
    {
        jQuery('#'+dispId).show();
        jQuery('#'+eleId).hide();
        jQuery('#'+dispId).removeClass('black_text2');
   }
}
//Simple search related JQ function start here.
function addSimpSrchEventJQ(colrId, crossId)
{
    jQuery("#" + colrId).addClass("black_text");
    jQuery("#" + crossId).show();
}

function resetSimpSrchEventJQ(selId, crossId)
{
    if(selId == 'service_location')
    {
        jQuery("#" + selId).val(ziptext_nl);
        jQuery("#" + selId).removeClass("black_text");
        jQuery("#" + selId).addClass("gray_text");
    }
    else if(selId == 'dealer_location')
    {
        jQuery("#" + selId).val(dealerText_nl);
        jQuery("#" + selId).removeClass("black_text");
        jQuery("#" + selId).addClass("gray_text");
    }
    else if(selId == 'search_text')
    {
        jQuery("#" + selId).val(searchFavKeyword);
        jQuery("#" + selId).removeClass("black_text");
        jQuery("#" + selId).addClass("gray_text");

        ajaxPostUpdater('listFavorite'+fileMidName+'.php');
    }
    else
    {
        jQuery("#" + selId).val("");
        jQuery("#" + selId).removeClass("black_text");
    }
    jQuery("#" + crossId).hide();
}

function resetSimpSrchEventPriceYearJQ()
{
    var argv = resetSimpSrchEventPriceYearJQ.arguments;
    var argc = argv.length;
    for (var i = 0; i < argc; i++)
    {
        jQuery("#"+argv[i]).val("");
        jQuery("#"+argv[i]).removeClass("black_text");
    }
    jQuery("#"+argv[2]).hide();
}
// Service Index class for new layout
function toggleServiceBoxNl(srvcId)
{
    var screenWidth=jQuery(document).width();
    var screenheight=jQuery(document).height();

    jQuery('#jquery-srvc-overlay').show();
    jQuery('#jquery-srvc-overlay').css({'width' : screenWidth, 'height' : screenheight});

    if(srvcId == 'srvc_cat_cls')
    {
        jQuery('#map_dom_list').hide();
        jQuery('#service_map_box').hide();
        jQuery('#serv_cat_list').toggle();
        jQuery('#srvc_cat_cls').toggleClass('pop_active');
        jQuery('#srvc_location_cls').removeClass('pop_active');
    }
    if(srvcId == 'srvc_location_cls')
    {
        jQuery('#serv_cat_list').hide();
        jQuery('#service_map_box').hide();
        jQuery('#map_dom_list').toggle();
        jQuery('#srvc_location_cls').toggleClass('pop_active');
        jQuery('#srvc_cat_cls').removeClass('pop_active');
    }
}

function toggleDealerMapBoxNl()
{
    var screenWidth=jQuery(document).width();
    var screenheight=jQuery(document).height();

    jQuery('#jquery-srvc-overlay').show();
    jQuery('#jquery-srvc-overlay').css({'width' : screenWidth, 'height' : screenheight});

    jQuery('#map_dom_list').toggle();
    jQuery('#map_dom_active').toggleClass('pop_active');
}

function hideSerivceOverlay()
{
    jQuery('#serv_cat_list').hide();
    jQuery('#map_dom_list').hide();
    jQuery('#service_map_box').hide();

    jQuery('#map_dom_list').hide();
    jQuery('#map_dom_active').removeClass('pop_active');

    jQuery('#srvc_location_cls').removeClass('pop_active');
    jQuery('#srvc_cat_cls').removeClass('pop_active');
    jQuery('#jquery-srvc-overlay').hide();
    jQuery('#jquery-srvc-overlay').css({'width' : '', 'height' : ''});
}

/*Get Query String from the URL*/
function getQuerystring(key, default_)
{
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}
function replaceQueryString(url,param,value){

    var re = new RegExp("([?|&])" + param + "=.*?(&|$)","i");
    if (url.match(re))
        return url.replace(re,'$1' + param + "=" + value + '$2');
    else
        return url + '&' + param + "=" + value;
}

function getScrollPosition()
{
    jQuery('input[name=hideScrollTop]').val(jQuery(window).scrollTop());
}
function getAccessories(v1,siteCode)
{
   var conStr = '';
   var val = v1.value;
   var adId;
   if((document.location.href.match(/extra/i) == 'extra') && (document.location.href.match(/admin/i) == 'admin'))
   {
       var conStr = 'isAdmin=1&';
   }
   if(val=='' || val<=0)
   {
        alert(msgDefault);
        v1.selectedIndex = oldValue;
        return false;
   }
   adId = getQuerystring('id_machine');

   jQuery.post('http://'+location.host+'/ajaxListAcc.php',conStr+'ajxifrm=1&adTypeOfAcc='+val+'&adId='+adId,function(data){
       if(_isNLSite == 1)
       {
           if(data.indexOf('exist') == -1)
           {
               jQuery('#accessories').show();
               jQuery('#acc').html(data);
           }
           else
           {
              // No Accesory exists for this type
               jQuery('#accessories').hide();
           }
           setGreyColor();
       }
       else
           jQuery('#acc').html(data);
   });
   addRemoveMand(document.machinepost.id_sub_type);
   if(subType > 0)
       chkCat(subType);
   RemoveGroups('post_make');
   machineTypeChange(document.machinepost.id_machine_type,document.machinepost.id_make,V_MAKE,'','POST','');
   subTypeChange(document.machinepost.id_machine_type,document.machinepost.id_sub_type,V_SUB_TYPE,'POST');
   catSubTypeChange(document.machinepost.id_sub_type,document.machinepost.id_cat_sub_type,V_CAT_SUB_TYPE,'POST');

   return false;

}
function isAllowDistance(val)
{
    if(val != '' && val != dealerText_nl)
    {
        var distanceDis='';
        var slideDis=false;
        jQuery('#id_distance,#id_km').removeClass('opacity_class');
    }
    else
    {
        var distanceDis='disabled';
        var slideDis=true;
        jQuery('#dealerDistance,#serviceDistance').val('0');
        jQuery('#slider').slider('value', '0');
        jQuery('#id_distance,#id_km').addClass('opacity_class');
    }

    jQuery('#dealerDistance,#serviceDistance').attr('disabled', distanceDis);
    jQuery('#slider').slider({disabled: slideDis});
}

function quickAllowDistance(val)
{
    var allow = '';
    for(var i=0; i < arrTownDomi.length; i++)
    {
        var nm = arrTownDomi[i].value;

        if(nm.toLowerCase() == val.toLowerCase() && arrTownDomi[i].id != '')
        {
            allow=1;
            break;
        }
    }

    isAllowDistance(allow);
}

function ajaxSearchByText(e,o,p)
{
    var p;
    if(o=='f') {
        jQuery('#search_text').addClass('black_text');
        jQuery('#search_text').removeClass('gray_text');
        if(jQuery('#search_text_cross').length>0)
            jQuery('#search_text_cross').show();

        if(idiv('search_text').value==idiv('search_text').defaultValue)idiv('search_text').value='';
    }
    else if(o=='b') {
        if(jQuery('#search_text').val()=='')
        {
            jQuery('#search_text').removeClass('black_text');
            jQuery('#search_text').addClass('gray_text');
        }
        if(idiv('search_text').value=='')idiv('search_text').value=idiv('search_text').defaultValue;
    }
    else if(o=='k') {

        if(e.keyCode == 13) {
            if(idiv('search_text').value!=''&&idiv('search_text').value!=idiv('search_text').defaultValue)
                ajaxPostUpdater(p);
            return true;
        }
    }
    else if(o=='g') {
        if(idiv('search_text').value != '')
            ajaxPostUpdater(p);
    }
    else if(o=='s') {
        ajaxPostUpdater(p);
    }
    else
        return false;
}

function ajaxPostUpdater(p)
{
    if(typeof alfn == 'undefined') alfn=document.sortl;

    var u=_su+'/'+p;
    if(idiv('search_ad'))
        u += '?search_ad='+idiv('search_ad').value;
    else
        u += '?search_ad=go';

    var pars=jQuery(alfn).serialize();
    jQuery.post(u,pars,function(data){
        var respArr=data.split('@@$#$@@');

        if(respArr[1] == 'noAd:0')
        {
            opt = jQuery('input[name=opt]').val();
            if(opt.match(/expired|sold|hold/))
                p += '?opt='+opt;

            window.location.href=p;
            return false;
        }

        jQuery('#more_list').html(respArr[0]);
        if(_isNLSite == 1 && respArr[1]) {
            var statusarr = respArr[1].split('@');
            for(var j=0; j < statusarr.length; j++) {
                var status_arr = statusarr[j].split(':');
                jQuery('#count_'+status_arr[0]).html(status_arr[1]);
            }
            jQuery('#ajxifrm').val('');
        }

        return false;
    });
}

// Mark vehicle sold/hold/not for sale Using ajax in New layout listOwner ad page
function ajxChangeAdStatusNL(url)
{
    pars='ajxifrm=A';
    pageURL=url+'&'+pars;
    jQuery.post(pageURL,'',function (data){
        if(data.match(/<html>/))
        {
            jQuery.fn.colorbox({
                   html:data
                });
        }
        else
            notificationBox(data);
    });

    return false;
}

function removeParamFromURL(URL,param)
{
    URL = String(URL);
    var regex = new RegExp( "\\?" + param + "=[^&]*&?", "gi");
    URL = URL.replace(regex,'?');
    regex = new RegExp( "\\&" + param + "=[^&]*&?", "gi");
    URL = URL.replace(regex,'&');
    URL = URL.replace(/(\?|&)$/,'');
    regex = null;
    return URL;
}

/** This function is return whole url with append of selected search criteria */
function cleanGenFrmUrl(qs,act)
{
    var arrEacapeEleVal=['Hakusana','Maakunta, kunta tai postinro','Esim. "helsinki" tai "00100"','Keyword','Domicile, town or zip','For example "helsinki" or "00100"','Enter keyword here','Näytä','Show'];
    var l=qs.elements.length;
    var u='?';

    for(var i = 0; i < l; i++)
    {
        var e=qs.elements[i];

        if(jQuery.inArray(e.value, arrEacapeEleVal) != -1)
            continue;

        if(e.type == 'select-multiple')
        {
            var si=new Array();
            var count=0;
            var k;
            while (e.selectedIndex != -1)
            {
                if (e.selectedIndex != 0)
                {
                    u=u+e.name+'='+e.options[e.selectedIndex].value+'&';
                    si[count++]=e.selectedIndex;
                }
                e.options[e.selectedIndex].selected=false;
            }

            for(k=0; k<si.length; k++)
                e.options[si[k]].selected=true;
        }
        else if(((e.type == 'checkbox' || e.type == 'radio') && e.checked && e.value))
        {
            u=u+e.name+'='+e.value+'&';
        }
        else if(e.value && !isblank(e.value) && e.type != 'checkbox' && e.type != 'radio')
        {
            if(qs.name == 'searchService' && e.name == 'free_text')
            {
                var gs=true;
                var uVal = e.value;

                for(var j=0; j < arrServiceList.length; j++)
                {
                    var sVal = arrServiceList[j].value;
                    if(sVal[0].toLowerCase() == uVal.toLowerCase() || sVal[1].toLowerCase() == uVal.toLowerCase())
                    {
                        act = baseUrl+'/palvelu/'+cleanRewriteUrl(sVal[1])+'/'+arrServiceList[j].id;
                        gs=false;
                        break;
                    }
                }

                if(gs)
                    u=u+e.name+'='+e.value+'&';
            }
            else if(e.name == 'distance')
            {
                if(e.value > 0)
                    u=u+e.name+'='+e.value+'&';
            }
            else if(e.value.indexOf('#') != -1)
                u=u+e.name+'='+escape(e.value)+'&';
            else
                u=u+e.name+'='+e.value+'&';
        }
    }

    if(u.length > 0)
        act = act + u.substr(0,u.length-1);

    window.location.replace(act);
    return false;
}

function notificationBox(msg)
{
    jQuery('#notification_box').show();
    jQuery('#notification_box_msg').html(msg);
    jQuery('#notification_box').css('top',  (jQuery(window).height() - jQuery('#notification_box').height()) / 2+jQuery(window).scrollTop());
    jQuery('#notification_box').css('left', (jQuery(window).width() - jQuery('#notification_box').width()) / 2+jQuery(window).scrollLeft());
    jQuery('#notification_box').fadeOut(3000);
}

function changeAdIdForSMS(val)
{
    jQuery('#soldVehicleSMSTxt').html(val);
}

function resetOwnAdForm(pg,crossId)
{
    jQuery("#" + crossId).hide();
    jQuery("#search_text").removeClass("black_text");
    jQuery("#search_text").addClass("gray_text");
    jQuery('#search_text').val(document.getElementById('search_text').title);
    idiv('search_text').defaultValue = jQuery('#search_text').val();
    ajaxPostUpdater(pg);
}

function emailCounter(id_netti_user,sCode)
{
    if(sCode == 'NA' || sCode == 'NM' || sCode == 'NK' || sCode == 'NT' )
        url = '/vifMailLinkCounter.php';
    else if(sCode == 'NH')
        url = '/hifMailLinkCounter.php';
    else if(sCode == 'NP')
        url = '/pifMailLinkCounter.php';
    else if(sCode == 'NV')
        url = '/bifMailLinkCounter.php';
    else if(sCode == 'NF' || sCode == 'KP' || sCode == 'EL' )
        url = '/iifMailLinkCounter.php'

    if(sCode == 'NF' || sCode == 'KP' || sCode == 'EL' )
    {
        var pars = '';
-         new Ajax.Request('http://'+location.hostname+url+'?id_netti_user='+id_netti_user, {parameters: pars});
    }
    else
        jQuery.get('http://'+location.hostname+url,'id_netti_user='+id_netti_user);
}

function showHideAdFields(selectedVal,formObj)
{
    if(selectedVal != '')
    {
        if(document.getElementById('id_make'))
        {
            if(formObj.make)
                formObj.make.value='';
            document.getElementById('id_make').className = 'table_row_hide';
        }
        if(document.getElementById('id_model'))
        {
            if(formObj.model)
                formObj.model.value='';
            document.getElementById('id_model').className = 'table_row_hide';
        }
        if(document.getElementById('id_year'))
        {
            if(formObj.year)
                formObj.year.value='';
            document.getElementById('id_year').className = 'table_row_hide';
        }
        if(document.getElementById('id_price'))
        {
            if(formObj.price)
                formObj.price.value='';
            document.getElementById('id_price').className = 'table_row_hide';
        }
        if(document.getElementById('id_mileage'))
        {
            if(formObj.mileage)
                formObj.mileage.value='';
            document.getElementById('id_mileage').className = 'table_row_hide';
        }
    }
    else
    {
        if(document.getElementById('id_make'))
            document.getElementById('id_make').className = 'table_row_show';
        if(document.getElementById('id_model'))
            document.getElementById('id_model').className = 'table_row_show';
        if(document.getElementById('id_year'))
            document.getElementById('id_year').className = 'table_row_show';
        if(document.getElementById('id_price'))
            document.getElementById('id_price').className = 'table_row_show';
        if(document.getElementById('id_mileage'))
            document.getElementById('id_mileage').className = 'table_row_show';
    }
}
var intVal_u;
function chkLenLoad()
{
    setTimeout('chkloginLenth()', 3000);
}

function checkLoginId()
{
    if(document.getElementById('passwd').value.length > 0)
    {
        clearTimeout(intVal_u);
        removePassImg();
        return;
    }
    intVal_u = setTimeout('checkLoginId()',100);
}

function chkloginLenth()
{
    if(document.getElementById('loginid'))
    {
        var unameLength = document.getElementById('loginid').value.length;
        if(unameLength > 0)
        {
            removePassImg();
            removeUserNameImg();
        }
    }
}
function deleteListOwnerAd(url, ownerPageName) {
    if (confirm(msgDeleteConfirm)) {
        var pars = "&ajxifrm=A";

        jQuery.post(url, pars, function (data) {
            jQuery.fn.colorbox.close();
            notificationBox(data);
            jQuery("#ajxifrm").val("A");
            ajaxPostUpdater(ownerPageName);
        });
    }
}
function confirmDelSeachAgent(url,sCode)
{
    if(confirm(msgDeleteConfirm))
    {
        jQuery.post(url,'',function(data){
            var sfa=data.split('#@#');
            if(_isNLSite == 1)
                notificationBox(sfa[0]);
            else
            {
                jQuery('#message').addClass('inline_msg mt10');
                jQuery('#message').html(sfa[0]);
            }
            jQuery('#parentid_'+sfa[1]).remove();
            jQuery('#message_'+sfa[1]).remove();

            jQuery('#count_fa').html(sfa[2]);
            var color = 'odd';

            jQuery('div[id*=parentid_]').each(function(){
                jQuery(this).attr('class',color);
                if(color == 'even')
                    color = 'odd';
                else
                   color = 'even';
            });
        });
    }
}

function ajaxcall(formObj,scriptName)
{
    formObj.ajxifrm.value = 'A';
    var pars=jQuery(formObj).serialize();
    jQuery.post('http://'+location.hostname+scriptName,pars,function(data){

        var arrData = data.split('#@#@#');
        if(arrData.length == 2 && arrData[1] == 1)
            jQuery('#invalidCaptchaMsg').html(arrData[0]);
        else
        {
            jQuery.fn.colorbox.close();
            if(getQuerystring('outSide') == '1' && location.hostname.match(/nettivene/i))
                jQuery('#contAjaxRequest').html('<div id="msg">'+arrData[0]+'</div>');
            else if(_isNLSite == 1)
                notificationBox(arrData[0]);
            else
                jQuery('#contAjaxRequest').html(arrData[0]);
        }

        if(jQuery("#badAd_vif"))
            jQuery("#badAd_vif").css("display", "none");
    });
    return false;
}

function ajaxcallSDS(formObj,scriptName)
{
    var pars=jQuery(formObj).serialize();
    jQuery.post('http://'+location.hostname+scriptName,pars+'&sd=1&ajxifrm=A&ajx=1',function(data){
        var arrSDSData = data.split('#@#@#');

        if(arrSDSData.length == 2 && arrSDSData[1] == 1)
            jQuery('#invalidCaptchaMsg').html(arrSDSData[0]);
        else
        {
            jQuery.fn.colorbox.close();
            notificationBox(arrSDSData[0]);
        }
    });
    return false;
}
function dealerClickStat(dealerId)
{
    jQuery.post('http://'+location.hostname+'/bannerCounter.php','dealerId='+dealerId+'&dealerHomePgStat=Y');
    return false;
}
function priceChange(v1,v2,curval,sign)
{
    if(sign)
        sign=sign;
    else
        sign="€";
    changeDropDownValue(v1,v2,curval,sign)
}
function changeDropDownValue(v1,v2,curval,sign)
{
    if(v1.selectedIndex<1)
        var st=1;
    else
        var st=v1.selectedIndex;
    if(curval==''&&v2.selectedIndex>0)
        curval=v2.options[v2.selectedIndex].value;
    var tot=v1.length;
    v2.length=1;
    for(i=st,j=1;i<tot;j++,i++)
    {
        if(parseInt(v1.options[i].value)>=1000)
        {
            var len=v1.options[i].value.length;
            var disp=v1.options[i].value;
            var disp1=disp.substr(0,len-3);
            var disp2=disp.substr(len-3,len);
            disp=disp1+' '+disp2;
        }
        else
            var disp=v1.options[i].value;
        if(sign!='')
            disp=disp+' '+sign;
        temp=new Option(disp,v1.options[i].value);
        eval(v2.options[j]=temp);
        if(curval==v1.options[i].value)
            v2.selectedIndex=j;
    }
}
function ajaxServiceCall(formObj,containerName)
{
    formObj.ajxifrm.value = 'A';
    var pars=jQuery(formObj).serialize();
    jQuery.post('http://'+location.hostname+'/viewService.php',pars,function(data){
        var arrData = data.split('#@#@#');
        if(arrData.length == 2 && arrData[1] == 1)
            jQuery('#invalidCaptchaMsg').html(arrData[0]);
        else
        {
            jQuery.fn.colorbox.close();
            notificationBox(data);
        }
    });
    return false;
}
function checkServLogin(frmObj)
{
    if(frmObj.passwd.value == '')
    {
        alert(msgMandet);
        return false;
    }

    var pars='ajxServLogin=1&id='+frmObj.id.value+'&passwd='+frmObj.passwd.value;
    jQuery.post(baseUrl+'/editServiceLogin.php',pars,function(data){
        jQuery('#passwd').val('');
        jQuery('#msgLoginError').empty();
        if(data=='success')
        {
            jQuery('#service_login').hide();
            editServiceDialog(frmObj.id.value);
        }
        else
            jQuery('#msgLoginError').html('<table width="100%" border="0" cellspacing="3" cellpadding="0"><tr><td height="27" class="inline_msg">'+data+'</td></tr></table>');
    });
    return false;
}
function editServiceDialog(id)
{
    jQuery.fn.colorbox({
        href:baseUrl+'/editService.php?id='+id,
        onComplete:function() {
            if(jQuery('#editServFailed').text() == 'error')
                window.location.reload();
        }
    });
}
function checkForServPass(theForm)
{
    if(!emailInvalid(theForm.email.value))
    {
        alert(msgInvalidEmail);
        theForm.email.focus();
        return false;
    }
    else if(!theForm.user_code.value)
    {
        alert(magWordMatch);
        theForm.user_code.focus();
        return false;
    }

    var pars=jQuery(theForm).serialize();
    jQuery.post(baseUrl+'/forgotServPass.php',pars,function(data){
        if(data.substr(0,7) == 'success')
        {
            notificationBox(data.substr(7));
            jQuery.fn.colorbox.close();
        }
        else
            jQuery('#msgForgotPassError').html('<table width="100%" border="0" cellspacing="3" cellpadding="0"><tr><td height="27" class="inline_msg">'+data+'</td></tr></table>');
    });
    return false;
}
function errorMsgAlert(id,msg)
{
    jQuery('#'+id+'_ele').addClass('highlight').focus();
    alert(msg);
    return false;
}

function removeErrorClass(id)
{
    jQuery('#'+id).removeClass('highlight');
}
function checkServiceField(theForm)
{
    if(jQuery('#dealerService').val() != 'Y')
    {
        if(theForm.address.value && !checkAddContTime(theForm.address.value))
            return errorMsgAlert('address',msgAddBlank);
        else if(theForm.zip.value && !checkZip(theForm.zip.value))
            return errorMsgAlert('zip',msgZip);
        else if(isblank(theForm.email.value))
            return errorMsgAlert('email',msgBlankEmail);
        else if(!emailInvalid(theForm.email.value))
            return errorMsgAlert('email',msgInvalidEmail);
        else if(theForm.phone.value && !check(theForm.phone.value))
            return errorMsgAlert('phone',msgPhoneFormat);
        else if(theForm.mobile.value && !check(theForm.mobile.value))
            return errorMsgAlert('mobile',msgMobileFormat);
        else if(theForm.fax.value && !check(theForm.fax.value))
            return errorMsgAlert('fax',msgFaxFormat);
    }

    var pars='ajxServEdit=1&'+jQuery(theForm).serialize();
    jQuery.post(baseUrl+'/editService.php',pars,function(data){
        if(data.substr(0,7) == 'success')
        {
            notificationBox(data.substr(7));
            jQuery.fn.colorbox.close();
        }
        else
            jQuery('#msgLoginError').html('<table width="100%" border="0" cellspacing="3" cellpadding="0"><tr><td height="27" class="inline_msg">'+data+'</td></tr></table>');
    });
    return false;
}
function loadDefBlurNew(txtObj,defVal)
{
    jQuery('textarea[name='+txtObj.name+']').focus(function() {

        if(txtObj.value == defVal)
            txtObj.value = '';
    });
    jQuery('textarea[name='+txtObj.name+']').blur(function() {
        if(txtObj.value == '')
        {
            txtObj.value = defVal;
            txtObj.style.color = '#666666';
        }
    });
    jQuery('textarea[name='+txtObj.name+']').click(function() {
        if(txtObj.value == defVal)
            txtObj.value = '';
    });

    if(txtObj.value != defVal)
        txtObj.style.color = '#000000';
    else
        txtObj.style.color = '#666666';
}
function addTownNL(t,st)
{
    var addTown=true;
    var dup = 0;
    var valDropDown = '';

    townTxt=t.options[t.selectedIndex].text;
    townVal=t.options[t.selectedIndex].value;

    if(townVal == '' || townVal == '0')
        addTown=false;
    else
    {
        domTxt = idiv((t.name == 'id_town_bubble') ? 'lastDomicileBubble' : 'lastDomicile').value;

        jQuery('div[id^=id_sel_town_]').each( function() {
            var getTownArr= jQuery(this).attr('id').split('id_sel_town_');
            var townVal2 = getTownArr[1];

            if (townVal == townVal2)
            {
                addTown=false;
            }
            else if(jQuery('div[id*='+townVal+'][id^=id_sel_town]').length>0)
            {
                if(jQuery('div[id*=_'+townVal+'-][id^=id_sel_town]').length>0 || jQuery('div[id*=-'+townVal+'-][id^=id_sel_town]').length>0 || jQuery('div[id*=-'+townVal+'@][id^=id_sel_town]').length>0)
                    addTown=false;
            }
            else if(townVal.match(/@/))
            {
                arrTown=townVal.split('@');

                arrSelectedTown=arrTown[0].split('-');
                for(var i=0;i < arrSelectedTown.length;i++)
                {
                    if(arrSelectedTown[i] == townVal)
                    {
                        jQuery('div[id^=id_sel_town_]').remove();
                        addTown=true;
                    }
                }
            }
            else if(townVal2.match(/@/))
            {
                arrTown=townVal2.split('@');

                arrSelectedTown=arrTown[0].split('-');
                for(var j=0;i < arrSelectedTown.length;j++)
                {
                    if(arrSelectedTown[j] == townVal2)
                    {
                        jQuery('div[id^=id_sel_town_]').remove();
                        addTown=true;
                    }
                }
            }
            else if(townVal.match(/d/))
            {
                allTown=townVal.replace('d','');

                arrSelectedDom=tmpText.split(' -');
                arrTownTxt=townTxt.split(' -');

                if(arrSelectedDom[0] == domTxt)
                {
                    jQuery('div[id^=id_sel_town_]').remove();
                    addTown=true;
                }
            }
            else if(townVal2.match(/d/))
            {
                arrTown=townVal.replace('d','');

                arrSelectedDom=tmpText.split(' -');
                arrTownTxt=townTxt.split(' -');

                if(arrSelectedDom[0] == domTxt && (arrTownTxt[0]=='Kaikki' || arrTownTxt[0]=='Any'))
                {
                    jQuery('div[id^=id_sel_town_]').remove();
                    addTown=true;
                }
            }
        });

        if(addTown)
        {
            if(/-/g.test(townVal) == true)
            {
                jQuery('#town_list option').each(function(){
                    if(jQuery('#id_sel_town_close_'+this.value).length>0)
                        removeEntireDiv('id_sel_town_close_'+this.value,'town');
                });
            }
            if(t.name == 'id_town_bubble')
                valDropDown = domTxt+', '+townTxt+'  <span title="'+capResetSearch+'" alt="'+capResetSearch+'" class="grey_reset" id="id_sel_town_close_'+townVal+'" onclick="javascript:removeSelTownNL(this.id);"></span>';
            else
                valDropDown = domTxt+', '+townTxt+'  <span title="'+capResetSearch+'" alt="'+capResetSearch+'" class="grey_reset" id="id_sel_town_close_'+townVal+'" onclick="javascript:removeSelTownNL(this.id);"></span>';

            jQuery('#id_sel_town').append('<div id="id_sel_town_'+townVal+'">'+valDropDown+"</div>");
        }
    }
}
function removeSelTownNL(id)
{
    jQuery('#'+id).remove();
    removeEntireDiv(id,'town');
}
function removeDiv(id,type)
{
    var getId= type.split('id_sel_');
    removeEntireDiv(id,getId[1]);
    callAjax(document.adv);
}
function removeEntireDiv(id,val)
{
    getArr = id.split('id_sel_'+val+'_close_');
    jQuery('#'+id).remove();
    if(/\s/g.test(getArr[1]))
        jQuery('div[id*=id_sel_'+val+'_'+getArr[1]+']').remove();
    else
        jQuery('div[id=id_sel_'+val+'_'+getArr[1]+']').remove();
}

function toggleChkboxState(id, chkState)
{
    if(chkState == true)
        document.getElementById(id).disabled='disabled';
    else
        document.getElementById(id).disabled='';
}

function fbToolTip(fb_benefit_fbc,fb_fast_reg,fb_auto_reg,fb_fast_login,fb_one_click,fb_no_auto_share,fb_no_auto_post)
{
    $seconds = setTimeout(function() { fbToolTip(fb_benefit_fbc,fb_fast_reg,fb_auto_reg,fb_fast_login,fb_one_click,fb_no_auto_share,fb_no_auto_post); }, 1000);
    $timer = $timer + 1;
    if($timer == 2)
    {
        jQuery('#fb_tooltip').html(
                '<div class="fb_toolTipWrapper">'
                    +'<div class="fb_toolTipTop"></div>'
                    +'<div class="fb_toolTipMid">'
                    +fb_benefit_fbc+'<div class="mt15">'+fb_fast_reg+'<div class="small_text11 pl10">'+fb_auto_reg+'</div><br />'+fb_fast_login+'<div class="small_text11 pl10">'+fb_one_click
                    +'</div><br />'+fb_no_auto_share+'<div class="small_text11 pl10">'+fb_no_auto_post+'</div></div>'
                    +'</div>'
                    +'<div class="fb_toolTipBtm"></div>'
                +'</div>');
            jQuery('.fb_toolTipWrapper').fadeIn(50);
        clearTimeout($seconds);
    }
}
/* below 4 functions use in service index page */
function selectServFreeText(v)
{
    if(!v)
        v = jQuery('#free_text').val();

    jQuery('#free_text').val(v);
    jQuery('#id_recent_searches').hide();
    jQuery('#id_drop_arrow').removeClass('s_drop_arrow_o').addClass('s_drop_arrow');
}

var cs = 0;
var cText = '';
var lastServSearch = '';

function arrangeServListIndex()
{
    // Add data to let the hover know which index they have
    for(var i = 0; i < jQuery('#recent_search_list ul li,#id_suggestion_text ul li').size(); i++) {
        jQuery('#recent_search_list ul li,#id_suggestion_text ul li').eq(i).data('number', i);
    }
}

function navigateServList(direction)
{
    // Check if any of the menu items is selected
    if(jQuery('#recent_search_list ul li.sugge_select,#id_suggestion_text ul li.sugge_select').size() == 0)
        cs = -1;

    if(direction == 'up' && cs != -1) {
        if(cs != 0)
            cs--;
        else
            cs=jQuery('#recent_search_list ul li,#id_suggestion_text ul li').size() -1;
    } else if(direction == 'down') {
        if(cs != jQuery('#recent_search_list ul li,#id_suggestion_text ul li').size() -1)
            cs++;
        else
            cs=0;
    }

    setServListSelected(cs);
}

function setServListSelected(menuitem)
{
    jQuery('#recent_search_list ul li,#id_suggestion_text ul li').removeClass('sugge_select');
    jQuery('#recent_search_list ul li,#id_suggestion_text ul li').eq(menuitem).addClass('sugge_select');
    cText = jQuery('#recent_search_list ul li,#id_suggestion_text ul li').eq(menuitem).text();
}
