/* $Id: nk_common_50.js,v 1.3 2010/02/22 09:32:49 hetal Exp $ */

var _su='http://'+location.hostname;

function createXHR()
{
   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) {}
   return null; // no XHR support
}

function AjaxUpdater(updateDiv,url,extraAction)
{
    var xhr = createXHR();
    xhr.open("GET", url, true)
    xhr.setRequestHeader("Content-Type", "text/html;charset=UTF-8");

    xhr.onreadystatechange=function()
    {
        if(xhr.readyState == 4)
        {
            if(updateDiv)
                idiv(updateDiv).innerHTML=xhr.responseText;
            if(extraAction)
                eval(extraAction);
        }
    }
    xhr.send(null);
    return false;
}

function idiv(i)
{
    return document.getElementById(i);
}

/** Function for show/hide more search criteria */
function display_search()
{
    if(idiv('adv_option').style.display == 'inline')
        idiv('adv_option').style.display = 'none';
    else
        idiv('adv_option').style.display = 'inline';
}
/** function for nk_searchMachine.ihtml */
function check_search()
{
    vehidRegno=document.search.veh_id_reg_no.value;

    /* Strips blank spaces from left and right */
    var lre=/^\s*/;
    var rre=/\s*$/;

    vehidRegno=vehidRegno.replace(lre,"");
    vehidRegno=vehidRegno.replace(rre,"");

    if(isblank(vehidRegno))
    {
        /** When input field is blank */
        alert(msgBlankSearchMachine);
        document.search.veh_id_reg_no.focus();
        return false;
    }
    else if(vehidRegno.match(/^[0-9]{1,}$/))
    {
        location.href="viewMachine.php?id_machine="+vehidRegno;
    }
    else if(vehidRegno.match(/^[0-9a-zA-ZåÅäÄöÖÁÀÉÈÒÓÙÚáàèéòóùúÝìíýÌÍ´\s-]{1,7}$/))
    {
        location.href="viewMachine.php?reg_no="+vehidRegno;
    }
    else
    {
        alert(msgInvalidIdRegno);
    }
    return false;
}

function getPage(){
  url    = window.location.href;
  page   = window.location.href.toString().match(/\/([^\/]+)(#)?$/)[1];
  page   = page.replace(/\W/g,"");
  return page;
}
function maintainScrollUnload(e){
  page = getPage();
  var date = new Date()
  var date = new Date()
  var expdate = date.getTime()
  expdate += 5*60*1000; //expires in 5 minutes(milliseconds)
  date.setTime(expdate);

  if(page.match(/^(simpleSearch|listMachine|listAdvSearchFindAgent|listCategory)/)){
    document.cookie = 'scroll=' +page+ document.documentElement.scrollTop
                    + "; expires="+ date.toGMTString();
  }
  if(page.match(/^viewMachine/)){
    document.cookie = "prevpage="+page + "; expires="+ date.toGMTString();
  }
}
function maintainScrollLoad()
{
  var page=getPage();
  if( document.cookie.match(/prevpage=viewMachinephp/ ) )
    {
        var reg = new RegExp( "scroll="+page + "(\\d+)" );
        if( scroll = document.cookie.match(reg) )
        {
            document.documentElement.scrollTop=scroll[1]-50;
        }
    }
}
if(!window.location.href.toString().match(/\/$/) && navigator.userAgent.indexOf('Firefox') > 0){
    if (window.addEventListener) {
      window.addEventListener("load", maintainScrollLoad, false);
      window.addEventListener("beforeunload", maintainScrollUnload, false);
    }
}
function car_quiz()
{
    window.open('carQuiz.php','ap','scrollbars=auto,resizable=yes,width=555,height=700');
    AjaxUpdater('car_quiz',_su + '/updateQuizCount.php');
}
/** Function to increase the hit counter of navigation_ad table */
function navigationHitCounter(id,urlNo)
{
    AjaxUpdater('',_su + '/navigationHitCounter.php?id='+id+'&urlNo='+urlNo);
}
// define global vars used in simple search and posting.
var textureName='';
var optChar='';
var optGroup='';
var textureGroup='';
var make_opt='';

function machineTypeChange(v1,v2,curval,curval_more,cond,extra)
{
    var id_make,j,i,z,make_value,make_text,makeOpt,machineid='';
    var bflag=1;

    //If browser is IE but version is not 6.0 then flag will be false
    if(navigator.appVersion.indexOf("MSIE") != -1 && !(parseFloat(navigator.appVersion.substr(navigator.appVersion.indexOf("MSIE")+5,3)) >= 6.0))
        bflag=0;
    if (navigator.appName=="Netscape" && !(parseFloat(navigator.appVersion) >= 4.8))
        bflag=0;

    if(cond != 'ADV')
        id_make="'"+curval+"'";
    else
        id_make=curval;

    //holds the seleted machine type.
    var typeId='';

    if(v1.selectedIndex >= 0)
        typeId=v1.options[v1.selectedIndex].value;
    
    if(v1 && typeId == 11)
    {
        v1.selectedIndex=0;
        if(cond != 'POST')
        {
            var motoUrl2;
            if(motoUrl.match(/login\.php/))
                motoUrl2=motoUrl.replace(/\/login(.*)/,'/simpleSearch.php?show=block&status=F&id_bike_type=16');
            else
                motoUrl2=motoUrl+'/simpleSearch.php?show=block&status=F&id_bike_type=16';

            window.open(motoUrl2);
        }
        else
            window.open(motoUrl+'&back=addEditVehicleImage.php');

        return;
    }

    if(v1)
    {
        if(v1.length)
        {
            if(v1.selectedIndex >= 0)
                machineid=new String(v1.options[v1.selectedIndex].value);
            else
                machineid='';
        }
        else
            machineid=v1;
    }
    textureName='';

    //while posting the ad, if no machine type is selected, don't dipslay makes.
    if(cond == 'POST' && machineid == '')
        return;

    if(machineid != '')     //Machine Type is selected
    {
        if(v2.length > 0 && v2.options[0].value == '')
        {
            v2.length=1;
            j=1;
        }
        else            //Posting Machine
        {
            v2.length=0;
            j=0;
        }

        for(i=0; i < m1.length; i++)
        {
            var goFlag=0;
            arrMakeInfo=(m1[i]).split('#');
            arrMakeTypeInfo=(arrMakeInfo[3]).split(',');

            for(k=0; k < arrMakeTypeInfo.length; k++)
            {
                if(arrMakeTypeInfo[k] == machineid)
                    goFlag=1;
            }
            if(goFlag == 0)
                continue;

            var make_value=arrMakeInfo[0];
            var make_text=arrMakeInfo[1];

            if(cond == 'POST' || cond == 'ADV' || arrMakeInfo[2] > 0)
            {
                /** OPTION GROUP MACHINE STARTS HERE */
                /* Changes has been made for displaying makes in alphabetical group. */
                if(make_text.match(/^[A-Za-zÅÖ]{1}/) && (!(navigator.userAgent.match(/Opera/))) && bflag == 1)
                {
                    optChar='';
                    optChar=make_text.substr(0,1);
                    optGroup='T';

                    if(textureName != optChar)
                    {
                        textureName=optChar;
                        textureGroup=document.createElement ('optgroup');
                        textureGroup.label=textureName;
                        v2.appendChild(textureGroup);
                    }
                }
                else
                    optGroup='F';

                if(optGroup != 'F' && textureName != '')
                {
                    make_opt=document.createElement('option');
                    make_opt.value=make_value;

                    if (navigator.userAgent.match(/IE/))
                        make_opt.innerText=make_text;
                    else
                        make_opt.text=make_text;

                    textureGroup.appendChild(make_opt);
                }
                else
                {
                    makeOpt=new Option(make_text,make_value);
                    eval('v2.options[j]=makeOpt');
                }
                /** OPTION GROUP MACHINE ENDS HERE */

                if(id_make.search("'"+make_value+"'") != -1)
                    v2.options[j].selected=true;

                if(id_make == make_value)
                    v2.options[j].selected=true;

                j++;
            }
        }
    }
    else
    {
        //When Machine Type is not selected (Simple Search)
        v2.length=1;
        j=1;

        for(i=0; i < m1.length; i++)
        {
            arrMakeInfo=(m1[i]).split('#');

            if(arrMakeInfo[2] > 0 || cond == 'ADV')
            {
                var make_value=arrMakeInfo[0];
                var make_text=arrMakeInfo[1];

                /** OPTION GROUP MACHINE STARTS HERE */
                if(make_text.match(/^[A-Za-zÅÖ]{1}/) && (!(navigator.userAgent.match(/Opera/))) && bflag == 1)
                {
                    optChar='';
                    optChar=make_text.substr(0,1);
                    optGroup='T';

                    if(textureName != optChar)
                    {
                        textureName=optChar;
                        textureGroup=document.createElement ('optgroup');
                        textureGroup.label=textureName;
                        v2.appendChild(textureGroup);
                    }
                }
                else
                    optGroup='F';

                if(optGroup != 'F' && textureName != '')
                {
                    make_opt=document.createElement('option');
                    make_opt.value=make_value;

                    if(navigator.userAgent.match(/IE/))
                        make_opt.innerText=make_text;
                    else
                        make_opt.text = make_text;

                    textureGroup.appendChild(make_opt);
                }
                else
                {
                    makeOpt=new Option(make_text,make_value);
                    eval('v2.options[j]=makeOpt');
                }
                /** OPTION GROUP MACHINE ENDS HERE */

                if(id_make.search("'"+make_value+"'") != -1)
                    v2.options[j].selected=true;

                if(id_make == make_value)
                    v2.options[j].selected=true;

                j++;
            }
        }
    }
}

//Function to change the subtype corresponding to machine type
function subTypeChange(v1,v2,curval,cond)
{
    //If the selected value is not passed in curval, then check whether any subtype is selected and
    //if yes, store it as curval.
    if(curval == '' && v2.selectedIndex > 0)
        curval=v2.options[v2.selectedIndex].value;

    //'s' -> simple search, 'POST'-> machine post/edit, 'ADV'->advamce Search
    if(cond == 's' || cond == 'POST' || cond == 'ADV')
        curval="'"+curval+"'";

    //holds the seleted machine type.
    var typeId='';

    if(v1.selectedIndex >= 0)
        typeId=v1.options[v1.selectedIndex].value;

    //holds the selected machine type.
    var opt;
    var j=0;
    v2.length=0;

    if(cond == 's') //For simple search display the 'Machine subtype' as default option.
    {
        opt=new Option(subtype,'');
        eval('v2.options[j]=opt');
        j++;
    }
    else if(cond == 'POST') //For Machine post/edit, display the select as default option.
    {
        opt=new Option(selectOpt,'');
        eval('v2.options[j]=opt');
        j++;
    }
    else if(cond == 'ADV') //For advance search display the 'Machine subtype' as default option.
    {
        opt=new Option(modelDefVal,''); // For Any Option
        eval("v2.options[j]=opt");
        j++;
    }

    if(typeId != '') //If the machine type is selected(machine post/edit, simple search and advanced search)
    {
        for(var i=0; i < st1.length; i++)
        {
            var goFlag=0;
            arrSubTypeInfo=(st1[i]).split('#');
            arrMachineTypeInfo=(arrSubTypeInfo[3]).split(',');

            for(k=0; k < arrMachineTypeInfo.length; k++)
            {
                if(arrMachineTypeInfo[k] == typeId)
                    goFlag=1;
            }
            if(goFlag == 0)
                continue;

            var subType_value=arrSubTypeInfo[0];
            var subType_text=arrSubTypeInfo[1];

            if(cond == 'POST' || cond == 'ADV' || arrSubTypeInfo[2] > 0)
            {
                if(subType_value != 4)
                {
                    opt=new Option(subType_text,subType_value);
                    eval('v2.options[j]=opt');

                    if(curval.search("'"+subType_value+"'") != -1)
                        v2.options[j].selected=true;

                    j++;
                }
            }
        }
    }
    else
    {
        for(var i=0; i < st1.length; i++)
        {
            arrSubTypeInfo=(st1[i]).split('#');

            var subType_value=arrSubTypeInfo[0];
            var subType_text=arrSubTypeInfo[1];

            if(cond == 'POST' || cond == 'ADV' || arrSubTypeInfo[2] > 0)
            {
                if(subType_value != 4)
                {
                    opt=new Option(subType_text,subType_value);
                    eval('v2.options[j]=opt');

                    if(curval.search("'"+subType_value+"'") != -1)
                        v2.options[j].selected=true;

                    j++;
                }
            }
        }
    }
}

//Function to change category sub type corresponding to category
function catSubTypeChange(subType,catSubType,curval,page)
{
    var kt=0;
    var typeId='';
    var list=new Array();
    var strIdCatSubType=new String('');

    getCategoryIndex(catSubType);

    if(subType)
    {
        if(subType.length)
        {
            for(var i=0; i < subType.length; i++)
            {
                if(subType.options[i].selected)
                {
                    list[kt]=subType.options[i].value;
                    kt++;
                }
            }
        }
        else
            catSubTypeid=subType;
    }

    if(page == 'POST')
    {
        catSubType.length=1;
        j=1;
    }
    else if(page == 'ADV')
    {
        catSubType.length=1; // For Any Option
        j=1;
    }
    else
    {
        catSubType.length=1;
        j=1;
    }

    if(subType.selectedIndex >= 0)
        typeId=subType.options[subType.selectedIndex].value;

    if(typeId != '')
    {
        for(var z=0; z<=kt; z++)
        {
            if(list[z] != '')
            {
                if(st[list[z]])
                {
                    arrCatSubType=(st[list[z]]).split(',');

                    for(i=0; i < arrCatSubType.length; i++)
                    {
                        var cat_sub_id=arrCatSubType[i];

                        arrCatSubTypeInfo=(cst[cat_sub_id]).split('#');

                        var goFlag=0;
                        var catSubType_value=cat_sub_id;
                        var catSubType_text=arrCatSubTypeInfo[0];

                        if(page == 's')
                        {
                            if(arrCatSubTypeInfo[1] > 0)
                                goFlag=1;
                        }
                        else
                            goFlag=1;

                        if(goFlag == 1)
                        {
                            if(strIdCatSubType.search("#"+catSubType_value+"#") == -1)
                            {
                                cOpt=new Option(catSubType_text,catSubType_value);
                                eval('catSubType.options[j]=cOpt');

                                for(var n=0; n < tempid.length; n++)
                                {
                                    if(catSubType_value == tempid[n])
                                        catSubType.options[j].selected=true;
                                }
                                // Condition to get elements selected in category sub type combo box while editing advance search
                                if(curval.search("'"+catSubType_value+"'") != -1)
                                    catSubType.options[j].selected=true;

                                if(catSubType_value == curval)
                                    catSubType.selectedIndex=j;

                                strIdCatSubType=strIdCatSubType+'#'+catSubType_value+'#,';

                                j++;
                            }
                        }
                    }
                }
            }
        }
    }
    else
    {
        catSubType.length=1;
        var j=1;

        if(page == 'ADV')
        {
            selOpt=new Option(modelDefVal,''); // For Any Option
            eval('catSubType.options[0]=selOpt');
        }
    }
}

// function to get category sub type id
var tempid=new Array();

function getCategoryIndex(catSubType)
{
    var m=0;
    tempid.length=0;

    if(catSubType.length)
    {
        for(var i=0; i < catSubType.length; i++)
        {
            if(catSubType.options[i].selected)
            {
                tempid[m]=catSubType.options[i].value;
                m++;
            }
        }
    }
}

//Function to change the town corresponding to domicile
function townChange(v1,v2,curval)
{
    //If the selected value is not passed in curval, then check whether any subtype is selected and
    //if yes, store it as curval.
    if(curval == '' && v2.selectedIndex > 0)
    curval=v2.options[v2.selectedIndex].value;

    //holds the selected domicile.
    var i,j=0,opt,typeId='';

    if(v1.selectedIndex >= 0)
        typeId=v1.options[v1.selectedIndex].value;

    v2.length=0;

    opt=new Option(selectOpt,'');
    eval("v2.options[j++]=opt");

    if(typeId != '') //If the domicile is selected(machine post/edit, simple search and advanced search)
    {
        for(i=0; i < t[typeId].length; i++)
        {
            opt=new Option(n[typeId][i],t[typeId][i]);
            eval("v2.options[j]=opt");

            if(curval.search(t[typeId][i]) != -1)
            v2.options[j].selected=true;
            j++;
        }
    }
}

//Function to change year list box options
function yearChange(v1,v2,curval)
{
    var i,j,temp,tot=v1.selectedIndex+1;

    if(tot == 1)
    tot=v1.options.length-1;

    v2.length=1;

    for(i=1,j=1; i<tot; j++,i++)
    {
        temp=new Option(v1.options[i].value,v1.options[i].value);
        eval("v2.options[j]=temp");

        if(curval == v1.options[i].value)
        v2.selectedIndex=j;
    }
}

//Function to change price list box options
function priceChange(v1,v2,curval,sign)
{
    var st,i,j,temp,len,disp,disp1,disp2;

    if(v1.selectedIndex < 1)
    st=1;
    else
        st=v1.selectedIndex;

    var tot=v1.length;
    v2.length=1;

    for(i=st,j=1; i < tot; j++,i++)
    {
        if (parseInt(v1.options[i].value) >= 1000)
        {
            len=v1.options[i].value.length;
            disp=v1.options[i].value;
            disp1=disp.substr(0,len-3);
            disp2=disp.substr(len-3,len);
            disp=disp1+" "+disp2+" "+sign;
        }
        else
            disp=v1.options[i].value+" "+sign;

        temp=new Option(disp,v1.options[i].value);
        eval("v2.options[j]=temp");

        if(curval == v1.options[i].value)
        v2.selectedIndex=j;
    }
}

//Function to open new pop up window with variable width and height
function openImg(img_nm,w,h,nm)
{
    var myfeatures="directories=no,location=no,menubar=no,status=yes,titlebar=no,toolbar=no,resizable=yes,scrollbars=yes,width="+w+",height="+h+",left=0,top=0";

    if(nm == '')
    nm='new';

    var newImg=open(img_nm,nm,myfeatures);
    newImg.focus();
}

//Function opens window of desired size by giving proper alert window
function doLogin(msgVar,width,height)
{
    openImg("msgWin.php?opt="+msgVar,width,height,'newuser');
}
//Function to submit favorite page by adding/removing machines
function submitFav(thisV)
{
    frmObj = document.fav;
    var i,flag='N',checked_value,img_id='';

    for(i=1; i < document.fav.length; i++)
    {
        if(document.fav.elements[i].type == 'checkbox')
        {
            if(document.fav.elements[i].checked)
            {
                flag='Y';
                continue;
            }
        }
    }
    if(flag != 'Y')
    {
        alert(msgSelectAtLeastOne);
        return false;
    }
    if(thisV == 'remove')
        document.fav.opt.value='Rem';
    else
        document.fav.opt.value='Fav';

        /*  AJAX code starts    */

    if(thisV != 'remove')
    {
        idiv('loadingImg').style.display = 'inline';
        idiv('loadingImg2').style.display = 'inline';

        var pars = Form.serialize($(frmObj));
        var sub_url = document.fav.action;
        var xmlHttpReq=createXHR();

        xmlHttpReq.open('POST',sub_url,true);
        xmlHttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlHttpReq.setRequestHeader("Content-length", pars.length);
        xmlHttpReq.setRequestHeader("Connection", "close");
        xmlHttpReq.onreadystatechange=function() {
            if(xmlHttpReq.readyState == 4) {
                var str = xmlHttpReq.responseText;

                 arr = str.split("#");

                 if(arr[0] != '0')
                 {
                     idiv('favorite_cnt').innerHTML = '(' + arr[0] + ')';
                     idiv('favorite_cnt_end').innerHTML = '(' + arr[0] + ')';
                 }
                 if(arr[1] != '0')
                 {
                     idiv('common_messageX').innerHTML = arr[1] + ' ' + msgAddFavBig;
                     idiv('Add_To_Fav_End').innerHTML = arr[1] + ' ' + msgAddFavBig;
                 }
                 else
                 {
                     idiv('common_messageX').innerHTML = msgRptAddFav;
                     idiv('Add_To_Fav_End').innerHTML = msgRptAddFav;
                 }
                 idiv('common_messageX').style.display = 'block';
                 idiv('loadingImg').style.display = 'none';
                 idiv('Add_To_Fav_End').style.display  = 'block';
                 idiv('loadingImg2').style.display = 'none';
            }
        }
        xmlHttpReq.send(pars);

        //  Remove checked items
        for(i=1; i < document.fav.length; i++)
        {
            if(document.fav.elements[i].type == 'checkbox')
            {
                if(document.fav.elements[i].checked)
                {
                    document.fav.elements[i].checked = false;

                    if(thisV != 'remove')
                    {
                        checked_value = document.fav.elements[i].value;
                        if(document.fav.elements[i].alt == "odd" || document.fav.elements[i].alt == "even")
                        changeClass(checked_value,'listing');
                    }
                    continue;
                }
            }
        }
        return false;
    }
    else
    {
        document.fav.submit();
    }

}

/* Argument 'label' can be the entity name you want to delete,
for exa., user,dealer,boat etc. and 'nm' can be the user name,
dealer name or boat id etc.*/
function newConfirmDel(ref,label,nm)
{
    if(confirm(msgNewDeleteConfirm+" "+label+", '" + nm + "'?"))
    window.location.replace(ref);
}

function confirmReset()
{
    if(confirm(msgConfirmReset))
        return true;

    return false;
}
function newConfirmCancel(valMsg,valFile)
{
    if(valMsg != '')
    {
        if(confirm(valMsg))
        {
            if(valFile)
                location.href=valFile;
            else
                location.href='home.php';
        }
        else
            return false;
    }
    else
    {
        if(valFile != '')
            location.href=valFile;
        else
            location.href='home.php';
    }
}
//To check login session of user in VIF while sumbitting
//question or giving answer, if user is not logged in
//a pop up window opens where he can log in
function checkQue(file,from)
{
    if(file.id_user.value == '')
    {
        if(from == 'O')
        openImg('../../popUpLogin.php?M=OnlyForRegisteredUser',350,320,'nk_login');
        else
            openImg('popUpLogin.php?M=OnlyForRegisteredUser',350,320,'nk_login');

        return false;
    }
    var flag='N';

    for(var i=0; i < file.elements.length;i++)
    {
        if(file.elements[i].type == 'text')
        {
            if(!isblank(file.elements[i].value))
            flag='Y';
        }
    }
    if(flag == 'N')
    {
        alert(msgMandet);
        return false;
    }
    return true;
}

//Function to return nothing, this is used sometimes
//to display tool tip on plain text by making trick
function returnVoid() {}

function RemoveGroups(selectId)
{
    var lChars= new Array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','Å','Ö');
    for(var chr=0; chr < lChars.length; chr++)
    {
        RemoveGroup(lChars[chr],selectId);
    }
}

function RemoveGroup(groupLabel,selectId)
{
    try
    {
        var selectList = document.getElementById(selectId);
        var eachGroup = selectList.firstChild;
        while (groupLabel != eachGroup.label)
        {
            eachGroup = eachGroup.nextSibling;
        }
        selectList.removeChild(eachGroup);
    }
    catch(er){}
}


// function to change town list according the selected domicile.
function partTownChange(ptype,town,curval,page)
{
    if(ptype)
    {
        if(ptype.length)
        {
            if (page == 'SELECTPART')
            {
                if(ptype.selectedIndex > -1 && ptype.selectedIndex > 0)
                    idPart=new String(ptype.options[ptype.selectedIndex].value);
                else
                    idPart='';
            }
            else
            {
                if(ptype.selectedIndex > -1)
                    idPart=new String(ptype.options[ptype.selectedIndex].value);
                else
                    idPart='';
            }
        }
        else
            partid=ptype;
    }
    if(page == 'simp')
    {
        townlist=curval.split(',');
    }
    if(page == 'POST')
    {
        town.length=1;
        j=1;
    }
    else if(page == 'ADV')
    {
        town.length=0;
        j=0;
    }
    else if (page == 'listService')
    {
        town.length=0;
        j=0;
    }
    else
    {
        town.length=1;
        j=1;
    }
    if(idPart != '')
    {
        if(tId[idPart])
        {
            for(i=0; i < tId[idPart].length; i++)
            {
                cvalue=new String(tId[idPart][i]);
                ctext=new String(tName[idPart][i]);

                cOpt=new Option(ctext,cvalue);
                eval("town.options[j]=cOpt");

                if(page == 'simp')
                {
                    for(k=0; k < townlist.length; k++)
                    {
                        if(cvalue == townlist[k])
                            town.options[j].selected=true;
                    }
                }
                else
                {
                    if(tId[idPart][i] == curval)
                        town.selectedIndex=j;
                }
                j++;
            }
        }
    }
    else
    {
        j=1;
        town.length=1;
    }
}

function categoryChange(category,subcategory,curval)
{
    if(category)
    {
        if(category.length)
        {
            if(category.selectedIndex > -1)
            {
                idCat=new String(category.options[category.selectedIndex].value);
            }
            else
                idCat='';
        }
        else
            idCat=category;
    }

    subcategory.length=0;
    j=0;

    if(idCat != '')
    {
        if(sId[idCat])
        {
            for(i=0; i < sId[idCat].length; i++)
            {
                if(sCnt[idCat][i] > 0)
                {
                    if(sAvail[idCat][i].match(/NK/))
                    {
                        cvalue=new String(sId[idCat][i]);
                        ctext=new String(sName[idCat][i]);

                        cOpt=new Option(ctext,cvalue);
                        eval("subcategory.options[j]=cOpt");

                        if(sId[idCat][i] == curval)
                                subcategory.selectedIndex=j;
                        j++;
                    }
                }
            }
        }
    }
    else
    {
        j=0;
        subcategory.length=0;
    }
}

function checkPage(theForm,pageVal)
{
    if(theForm.gotopage.value.match(/^[0-9]{1,3}$/))
    {
        if(theForm.gotopage.value != 0)
        {
            if(theForm.gotopage.value > pageVal)
            {
                alert(msgPageNotAvailable);
                return false;
            }
            else
                return true;
        }
        else
        {
            alert(notValidPageNumber);
            return false;
        }
    }
    else
    {
        alert(notPageVal);
        return false;
    }
}

//  Functions for changing background color of updated row(s) when posting question or answers for Boats.

function whiteBG()
{
    idiv('que_modal').value = '';
    var elements = document.getElementsByTagName("tr");
    for(var i = 0;i < elements.length;i++)
    {
        if(elements[i].id == "TR_BG" && elements[i].className == "bgyellow" )
        {
            elements[i].className = "bgwhite";
        }
    }
    setTimeout("yellowBG();",500);
}
function yellowBG()
{
    var elements = document.getElementsByTagName("tr");
    for(var i = 0;i < elements.length;i++)
    {
        if(elements[i].id == "TR_BG" && elements[i].className == "bgwhite")
        {
            elements[i].className = "bgyellow";
        }
    }
    setTimeout("oddevenBG();",500);
}
//      Function for doing normal background.
function oddevenBG()
{
    var elements = document.getElementsByTagName("tr");
    for(var i = 0;i < elements.length;i++)
    {
        if(elements[i].id == "TR_BG")
        {
            if(i % 2 == 0)
                elements[i].className = "even";
            else
                elements[i].className = "odd";
        }
    }
}

//      Simple dealer que-ans
function sd_ajaxQue(formObj,var_O)
{
    if(checkQue(formObj,var_O) != false )
    {
        var id_bike = formObj.id_machine.value;
        var pars = Form.serialize($(formObj));

        if(formObj.replyToQue.value == 0)
        {
            formObj.que.disabled=true;
            formObj.exchangeid.disabled=true;
            formObj.save.disabled=true;
            document.getElementById('loaderimg').style.display='inline';
        }
        /* replacing € with &euro; */
        pars = pars.replace(/%E2%82%AC/g,'%26euro%3B');

        var xmlHttpReq=createXHR();
        xmlHttpReq.open('GET','sd_questionAnswer.php?ajxQueAns=1&'+pars,true);
        xmlHttpReq.setRequestHeader("Content-Type", "text/html;charset=UTF-8");
        xmlHttpReq.onreadystatechange=function() {
            if(xmlHttpReq.readyState == 4) {
                var str = xmlHttpReq.responseText;
                idiv('submitXQA').innerHTML = str;
                setTimeout("whiteBG();",1000);
            }
        }
        xmlHttpReq.send(null);
        return false;
    }
    else
        return false;
}
function sd_ajaxLoadImage(id)
{
    var qa_id = id;

    if(document.getElementById('nk_id_user').value == "")
        return false;

    if(checkQue(document.frmqueans) != false )
    {
        var answer = document.frmqueans.replyToQue.value;
        var pars = Form.serialize($(document.frmqueans));

        if(answer == 1)
        {
            var loader_img_id='loaderimg'+qa_id;
            var ans_id='ans'+qa_id;
            var anssave_id='anssave'+qa_id;

            document.getElementById(ans_id).disabled=true;
            document.getElementById(anssave_id).disabled=true;
            document.getElementById(loader_img_id).style.display='inline';
        }

        /* replacing € with &euro; */
        pars = pars.replace(/%E2%82%AC/g,'%26euro%3B');

        var xmlHttpReq=createXHR();
        xmlHttpReq.open('GET','sd_questionAnswer.php?ajxQueAns=1&'+pars,true);
        xmlHttpReq.setRequestHeader("Content-Type", "text/html;charset=UTF-8");
        xmlHttpReq.onreadystatechange=function() {
            if(xmlHttpReq.readyState == 4) {
                var str = response.responseText;
                idiv('submitXQA').innerHTML = str;
                setTimeout("whiteBG();",1000);
            }
        }
        xmlHttpReq.send(null);
    }
    else
        return false;
}

//      Fn. for Login modal
function loginmodal(opt,rPage)
{
    //  D => Simple Dealer , N => From View Page , P => Post Ad, RP => any given redirect page rPage
    if(opt == 'D')
    {
        pageURL = '../modalLogin.php?mainOnly=1';
        idiv('lightbox').style.left='65%';
    }
    else if(opt == 'N')
    {
        pageURL = 'modalLogin.php?mainOnly=1';
        idiv('lightbox').style.left='40%';
    }
    else if(opt == 'P')
    {
        pageURL = 'modalLogin.php?mainOnly=1&postad=1';
        idiv('lightbox').style.left='40%';
    }
    else if(opt == 'RP')
    {
        pageURL = 'modalLogin.php?mainOnly=1&redirectPage='+rPage;
        idiv('lightbox').style.left='40%';
    }
    else if(opt != 'P' && location.href.search('advSearch') == -1)
        document.getElementById('que').blur();

    lightbox.prototype.content = pageURL;
    lightbox.prototype.activate();
    idiv('lightbox').style.top = '60%';
    idiv('lightbox').style.width = '295px';
}

function modalForm(frmObj)
{
    var flag='N';
    var page_from=frmObj.page_from.value;
    var login_page;

    if(frmObj.postad.value == 1)
        var returnURL='postAd.php';
    else if(frmObj.redirectPage && frmObj.redirectPage.value != '')
        var returnURL=frmObj.redirectPage.value;
    else
        var returnURL=location.href;

    if(page_from.search('simple_dealer') == -1)
        login_page='login.php?ajxLogin=1'
    else
        login_page='../login.php?ajxLogin=1'

    for(i=0; i < frmObj.elements.length;i++)
    {
        if(frmObj.elements[i].type == 'text')
        {
            if(!isblank(frmObj.elements[i].value))
                flag='Y';
        }
    }
    if(frmObj.passwd.value.split(' ').join('').length == 0)
        flag='N';

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

    if(flag == 'Y')
    {
        var pars=Form.serialize($(frmObj));
        var xmlHttpReq=createXHR();

        xmlHttpReq.open('GET',login_page + ((login_page.indexOf('?') > 0) ? '&' : '?') + pars,true);
        xmlHttpReq.setRequestHeader("Content-Type", "text/html;charset=UTF-8");
        xmlHttpReq.onreadystatechange=function() {
            if(xmlHttpReq.readyState == 4) {
                if(xmlHttpReq.responseText == 'success')
                    location.href=returnURL;
                else if(xmlHttpReq.responseText == 'toHomePage')
                    location.href = '/';
                else
                    idiv('msgLoginError').innerHTML = '<table width="100%" border="0" cellspacing="3" cellpadding="0"><tr><td height="27" class="message">' + xmlHttpReq.responseText + '</td></tr></table>';
            }
        }
        xmlHttpReq.send(null);

    }
    return false;
}

/**     Modal for SendLink   */
function sendlinkmodal(event,anchor_obj)
{
    Event.stop(event);
    var urlLink = anchor_obj.href + '&mainOnly=1';
    lightbox.prototype.content = urlLink;
    lightbox.prototype.activate();
    idiv('lightbox').style.top = "50%";
    idiv('lightbox').style.width = "255px";
}

//      Check send link form
function checkFL()
{
    if(isblank(document.sendlink.name.value))
    {
        alert(msgNameBlank);
        document.sendlink.name.focus();
        return false;
    }
    if(!document.sendlink.name.value.match(/^[a-zA-ZåÅäÄöÖÁÀÉÈÒÓÙÚáàèéòóùúÝìíýÌÍ´_\s-]{1,50}$/))
    {
        alert(msgNameBlank);
        document.sendlink.name.focus();
        document.sendlink.name.select();
        return false;
    }
    if(!emailInvalid(document.sendlink.userEmail.value))
    {
        alert(msgInvalidEmail);
        document.sendlink.userEmail.focus();
        return false;
    }
    if(isblank(document.sendlink.email.value))
    {
        alert(msgMandet);
        document.sendlink.email.focus();
        return false;
    }
    s=document.sendlink.email.value;
    removeSpace = s.replace(/ /g,"");
    str1=removeSpace.split(',');

    if(str1.length > 10)
    {
        alert(msgMoreThan10Mail);
        document.sendlink.email.focus();
        return false;
    }
    else
    {
        for(var m=0; m<str1.length; m++)
        {
            if(!emailInvalid(str1[m]))
            {
                alert(msgInvalidEmail);
                document.sendlink.email.focus();
                return false;
            }
        }
    }
    return true;
}
/** Function to change the video status. */
function changeVideoStatus(idAd,videoStatus,idReporter)
{
    var reporterSuffix;

    if(confirm(msgChangeStatus))
    {
        if(idReporter == '')
        {
            reporterSuffix='';
            idReporter='';
        }
        else
            reporterSuffix='_'+idReporter;

        var pars='id_machine='+idAd+'&video_status='+videoStatus+'&id_reporter='+idReporter+'&ajxifrm=A';
        AjaxUpdater('vStatus'+idAd+reporterSuffix,_su+'/extra/admin/changeVideoStatus.php?'+pars);
    }
    else
        return;
}
/** Function for confirmation when video ad is delete. */
function confirmVideoDelete(ref)
{
    if(confirm(msgDeleteVideoConfirm))
        window.location.replace(ref);
}
/**
Function to play the video at given id of element.
id_element=>id of element where to display the video.
videoUrl=>viewVideo.php file.
*/
function playVideo(id_element,videoUrl)
{
    AjaxUpdater(id_element,videoUrl+((videoUrl.indexOf('?') > 0) ? '&' : '?')+'ajxifrm=A');
}

/** Function to change part type and part category and vehicle type and related make model using Ajax. */
function ajaxPartCatChange(id_partTypeMake,id_partCatModel,id_partVehicle_type,chgFor,curVal)
{
    var divName;

        idiv('loadingImg_part').style.display='inline';

    /** Parse the required variables those are used in ajaxPartSearch.php file. */
    var ajaxPars='id_partTypeMake='+id_partTypeMake.value+'&id_partCatModel='+id_partCatModel.value;
        ajaxPars +='&idVehicleType='+id_partVehicle_type.value+'&chgFor='+chgFor+'&curSelVal='+curVal;

    if(chgFor == 'PT')
        divName='partCategory';
    else if(chgFor == 'VT')
        divName='make_model';
    else if(chgFor == 'MK')
        divName='model_change';
    else
        divName='partCategory';

    AjaxUpdater(divName,_su+'/ajaxPartSearch.php?ajxifrm=A&'+ajaxPars,'idiv("loadingImg_part").style.display="none";callAjaxPart(document.srch_part);');
}
/** Function to set default value for more search criteria of simple search. */
function blankCri()
{
    document.srch.id_domicile.value='';
    document.srch.id_town.length=1;
}
/** call Ajax function for search result counter on change elements value. */
function callAjax(frmObj)
{
    /** for write hidden parameter selected model & selected acc and validate inspected motmonth & motyear */
    var ajaxFName=_su + '/ajaxSearchCounter.php?ajxifrm=A&site=NK';
    if(frmObj.name == 'adv')
    {
        checkFa();
        return ajaxCounterChng(ajaxFName+'&frm=ADV&'+ cleanFrmUrl(frmObj),frmObj.name);
    }
    else if(frmObj.name == 'srch')
    {
        return ajaxCounterChng(ajaxFName+'&frm=SIMP&'+ cleanFrmUrl(frmObj),frmObj.name);
    }
}
/** Ajax Function for display total counter of vehicle which are belong to search criteria */
function ajaxCounterChng(searchUrl,frmName)
{
    var loadingImg='';
    var ajaxFname=searchUrl.replace('/#/ig','@');

    if(frmName == 'adv')
        loadingImg='loadingImg_src_chngCntAdv';
    else if(frmName == 'srch')
        loadingImg='loadingImg_src_chngCnt';

    idiv(loadingImg).style.display='inline';

    var xmlHttpReq=createXHR();
    xmlHttpReq.open('GET',ajaxFname);
    xmlHttpReq.setRequestHeader("Content-Type", "text/html;charset=UTF-8");
    xmlHttpReq.onreadystatechange=function()
    {
        if(xmlHttpReq.readyState == 4)
        {
            showResponse(xmlHttpReq.responseXML);
            idiv(loadingImg).style.display='none';
        }
    }
    xmlHttpReq.send(null);
    return false;
}
function callAjaxPart(frmElement)
{
    var ajaxFname=_su + '/ajaxSearchCounter.php?ajxifrm=A&site=NP&'+cleanFrmUrl(frmElement);

    idiv('loadingImg_part').style.display='inline';

    var xmlHttpReq=createXHR();
    xmlHttpReq.open('GET',ajaxFname);
    xmlHttpReq.setRequestHeader("Content-Type", "text/xml;charset=UTF-8");
    xmlHttpReq.onreadystatechange=function()
    {
        if(xmlHttpReq.readyState == 4)
        {
            showResponse(xmlHttpReq.responseXML);
            idiv('loadingImg_part').style.display='none';
        }
    }
    xmlHttpReq.send(null);
    return false;
}
/** 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')
           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 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;
}