/* $Id: np_common_60.js,v 1.2 2009/12/18 10:23:48 tejash Exp $ */

//Declaration of variable used in functions
var id_make='';
var id_model='';
var partid='';
var i=0;
var j=0;
var vehicleid='';
var make_value='';
var make_text=''
var model_value='';
var model_text=''
var goFlag=0;
var idPart='';
var cvalue='';
var ctext=''
var tot=0;
var dup=0;
var p='';
var makeid='';
var make=''
var selPartId='';
var disp='';
var val='';
var st='';
var selOpt='';
var pCat='';
var pId='';
var temp='';
var cOpt='';
var o='';
var partType='';
var makeOpt='';
var c='';
var modelOpt='';
var textureName='';
var textureGroup='';
var optChar='';
var optGroup='';

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 check_search()
{
    if(isblank(document.search.veh_id.value))
    {
        alert(msgBlankSearchPart);
        document.search.veh_id.focus();
        return false;
    }
    else
    {
        //If part id is there
        if(document.search.veh_id.value)
        {
            if(document.search.veh_id.value.match(/^[0-9]{1,}$/))
            {
                //Strips blank spaces from left and right
                var lre=/^\s*/;
                var rre=/\s*$/;

                document.search.veh_id.value=document.search.veh_id.value.replace(lre,"");
                document.search.veh_id.value=document.search.veh_id.value.replace(rre,"");

                location.href="viewPart.php?id_part="+document.search.veh_id.value;
            }
            else
            {
                alert(msgNumeric);
                document.search.veh_id.focus();
                return false;
            }
        }
    }
    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|listPart|listAdvSearchFindAgent|listCategory)/)){
    document.cookie = 'scroll=' +page+ document.documentElement.scrollTop
                    + "; expires="+ date.toGMTString();
  }
  if(page.match(/^viewPart/)){
    document.cookie = "prevpage="+page + "; expires="+ date.toGMTString();
  }
}
function maintainScrollLoad(){
  var page=getPage();
  if( document.cookie.match(/prevpage=viewPartphp/ ) ){
    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 rengas_count(linkFrom)
{
    AjaxUpdater('rengas_count',_su+'/updateRengasCount.php?linkFrom='+linkFrom);
}
/** Function to increase the hit counter of navigation_ad table */
function navigationHitCounter(id,urlNo)
{
    AjaxUpdater('',_su+'/navigationHitCounter.php?id='+id+'&urlNo='+urlNo);
}
//This method is Used in Simple Search and Part Post forms.
function vehicleTypeChange(v1,v2,curval,cond,v3)
{
    vehicleid='';
    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(isNaN(curval))
        id_make='';
    else
        id_make=curval;

    //While posting, if vehicle type is changed change Make and Model as well
    if(cond == 'POST' && v3.length > 0)
        v3.length=1;
    else if(cond == 'Y') //Simple Search
        v3.length=1;

    if(v1)
    {
        if(v1.length)
        {
            if(v1.selectedIndex > -1)
                vehicleid=new String(v1.options[v1.selectedIndex].value);
            else
                vehicleid='';
        }
        else
            vehicleid=v1;
    }

    if(vehicleid != '')     //Vehicle Type is selected
    {
        if(cond == 'Y' || (v2.length > 0 && v2.options[0].value == ''))
        {
            v2.length=1;
            j=1;
        }
        else if(cond == 'POST')             //Posting Vehicle
        {
            v2.length=1;
            j=1;
        }
        else
        {
            v2.length=0;
            j=0;
        }

        if(v2.length != 0)
            v2.selectedIndex=0;

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

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

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

            if(cond == 'POST' || cond == 'ADV' || arrMakeInfo[2] > 0)    //Posting Vehicle && Simple Search
            {
                /** OPTION GROUP PART STARTS HERE */

                /** changes has been made for displaying makes in option group wise.
                    i.e. Starting with char A will listed below A Group, same as for B to Z.
                */
                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 PART ENDS HERE */

                if(id_make == make_value)
                    v2.selectedIndex=j;

                j++;
            }
        }
        if(v2.selectedIndex == '' || v2.selectedIndex < 1)
            v2.selectedIndex=0;

        if((cond == 'POST' || cond == 'ADV') && v2.length > 0) //Posting Vehicle
            makeChange(v2,v3,'',cond,v1);
    }
    else
    {
        if(cond == 'ADV' )
        {
            v2.length=0;
            j=0;
        }
        else
        {
            v2.length=1;
            j=1;
        }
    }
}

function chkValFromArr(val,array)
{
	for(var i=0;i<array.length;i++)
	{
		if(array[i] == val)
			return true;
	}
	return false;
}

//Used in Simple Search, Advance Search and Vehicle Post forms.
function makeChange(v1,v2,curval,cond,v3,frmWhere)
{
    vehicleid='';

    if(isNaN(curval))
        id_model='';
    else
        id_model=curval;

    if(v1.selectedIndex > -1 || v1.selectedIndex > 0)
        makeid=new String(v1.options[v1.selectedIndex].value)
    else
        makeid='';

    if(v3)
    {
        if(v3.length)
        {
            if(v3.selectedIndex > -1)
                vehicleid=new String(v3.options[v3.selectedIndex].value)
            else
                vehicleid='';
        }
        else
            vehicleid=v3;
    }

    if(makeid != '')
    {
        if(cond == 'Y' || (v2.length > 0 && v2.options[0].value == ''))
        {
            v2.length=1;
            j=1;
        }
        else    //Posting Vehicle
        {
            v2.length=0;
            j=0;
        }
        if(cond == 'ADV')
        {
            //Remove first element which is just blank
            v2.length=0;
            j=0;
        }
        if(v2.length != 0)
            v2.selectedIndex=0;

        if(cond == 'ADV')
        {
            var make_value=v1.options[v1.selectedIndex].value+'#'+v1.options[v1.selectedIndex].text;
            var make_text=v1.options[v1.selectedIndex].text+': '+anyModel;

            modelOpt=new Option(make_text,make_value);
            eval('v2.options[j++]=modelOpt');
        }

        if(m[makeid].length > 0)
        {
			// assign model ids in array which is not dispaly in posting page
			var mpid=new Array(148,134,145,135,146,147,136,137,138);

            arrModel=(m[makeid]).split(',');

            for(i=0; i < arrModel.length; i++)
            {
				if(frmWhere == 'post' && chkValFromArr(arrModel[i],mpid))
					continue;

                var model_id=arrModel[i];
                arrModelInformation=(c[model_id]).split('#');
                var model_value=model_id;
                var model_text=arrModelInformation[0];
                var goFlag=0;

                //Simple Search
                if(cond == 'Y')
                {
                    //When Vehicle Type is also selected then get models for that Vehicle Type only
                    if(vehicleid != '')
                    {
                        arrVehicleTypeCounter=arrModelInformation[2].split(/[@,]/);

                        for(k=0; k < arrVehicleTypeCounter.length; k++,k++)
                        {
                            if(arrVehicleTypeCounter[k]==vehicleid && arrVehicleTypeCounter[k+1] > 0)
                            {
                                goFlag=1;
                                break;
                            }
                        }
                    }
                    else
                    {
                        if(arrModelInformation[1] > 0)
                            goFlag=1;
                    }
                }
                else
                {
                    if(cond == 'ADV')
                        goFlag=1;

                    if(vehicleid != '')
                    {
                        // Vehicle Posting
                        arrVehicleTypeCounter=arrModelInformation[2].split(/[@,]/);

                        for(k=0; k < arrVehicleTypeCounter.length; k++,k++)
                        {
                            if(arrVehicleTypeCounter[k]==vehicleid && arrVehicleTypeCounter[k+1] >= 0)
                            {
                                goFlag=1;
                                break;
                            }
                        }
                    }
                    else    //Admin -> Normal Vehicle Search (Without Vehicle Type)
                        goFlag=1;
                }

                if(goFlag == 1)
                {
                    modelOpt=new Option(model_text,model_value);
                    eval('v2.options[j]=modelOpt');

                    if(id_model == model_value)
                        v2.selectedIndex=j;

                    j++;
                }
            }
        }

        if(cond != 'ADV')
        {
            if(v2.selectedIndex == '' || v2.selectedIndex < 1)
                v2.selectedIndex=0;
        }
    }
    else
    {
        v2.length=1;
        var j=1;

        if(cond == 'ADV')
        {
            selOpt=new Option('                                          ','');
            eval('v2.options[0]=selOpt');
        }
    }
}

//Change part category according to part Type
function partCatChange(ptype,part_category,curval,page)
{
    /*
        This IF blocks are getting used in navigation From NP to other Nettix sites
        Used in posting page only at now.
    */
    var partUrl=window.location.href;

    if(ptype && ptype.selectedIndex >= 0 && partUrl.match(/addPart\.php/) && page == 'POST' && ptype.options[ptype.selectedIndex].value == 45)
    {
        ptype.selectedIndex=0;
        veneUrl=veneUrl.replace(/\&amp\;/g,'&');

        if(page != 'POST')
        {
            if(veneUrl.match(/login\.php/))
                veneUrl2=veneUrl.replace(/\/login(.*)/,'/simpleSearch.php?status=F&sid_boat_type=14');
            else
                veneUrl2=veneUrl+'/simpleSearch.php?status=F&sid_boat_type=14';

            window.open(veneUrl2);
        }
        else
            window.open(veneUrl+'&back=addEditBoatImage.php');

        return;
    }
    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 == 'POST')
    {
        part_category.length=1;
        j=1;
    }
    else if(page == 'ADV')
    {
        part_category.length=0;
        j=0;

        if(ptype.value == '24' || ptype.value == '38')
            document.getElementById('tyre_manufacturer').style.display='';
        else
        {
            document.getElementById('tyre_manufacturer').style.display='none';
            document.getElementById('id_tyre_manufacturer').value='';
        }

        if(ptype.value == '38')
            document.getElementById('rims_make').style.display='';
        else
        {
            document.getElementById('rims_make').style.display='none';
            document.getElementById('rims_make').text='';
        }
    }
    else
    {
        part_category.length=1;
        j=1;
    }

    if(idPart != '')
    {
        // Ref. Task [FR-6231] More details to Rims
        // Temporary if condition to display only new Tyre Sets Category listing in add/edit page
		arrTyreSet=new Array(154,155,156,157,158,159);

        if(pId[idPart])
        {
            for(i=0; i < pId[idPart].length; i++)
            {
                cvalue=new String(pId[idPart][i]);

                //Ref. Task [FR-6231] More details to Rims
                // Temporary if condition to display only new Tyre Sets Category listing in add/edit page
                if(ptype.options[ptype.selectedIndex].value == '38' && page =='POST')
                {
					if(!chkValFromArr(pId[idPart][i],arrTyreSet))
						continue;

                    ctext=new String(pCat[idPart][i]);
                }
                else
                    ctext=new String(pCat[idPart][i]);

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

                if(pId[idPart][i] == curval)
                    part_category.selectedIndex=j;
                j++;
            }
        }
    }
    else
    {
        //When part Type is not selected (Simple Search)
        j=1;
        part_category.length=1;
    }
}

function clearSelPartCat(v1,v2)
{
    if(v1.selectedIndex == ''  || v1.selectedIndex < 1)
    {
        v2.length=1;
        selOpt=new Option('                                                      ','');
        eval("v2.options[0]=selOpt");
    }
}
//Function to add selected values from 'Model' fields
//into 'Selected models' field, used in Advanced search page
function addModel(v1,v2)
{
    if(!(v1.id_model.selectedIndex >= 0))
        return;

    if(v1.id_model[v1.id_model.selectedIndex].value != '')
    {
        if(v2.options[0].value == '')
            document.adv.id_sel_model.length--;

        if(v2.selectedIndex == 1)
            v2.selectedIndex=0;

        tot=v2.length;
        dup=0;

        for(o=0; o<tot; o++)
        {
            var tmpValue2=v2.options[o].value;
            var tmpValue=v1.id_model[v1.id_model.selectedIndex].value;

            if(tmpValue == tmpValue2)
            {
                dup=1;
                alert(msgDupSelected);
                break;
            }
            else if(tmpValue.match(/^([0-9]{1,})$/i) && tmpValue2.match(/^([0-9]{1,})#/i))
            {
                makeid=tmpValue2.substr(0,tmpValue2.indexOf('#'));
                make=tmpValue2.substr(tmpValue2.indexOf('#')+1,tmpValue2.length);

                arrModel=(m[makeid]).split(',');

                for(i=0; i < arrModel.length; i++)
                {
                    if(tmpValue == arrModel[i])
                    {
                        dup=1;
                        alert(makeAllSelected);
                        break;
                    }
                }
            }
            else if(tmpValue.match(/^([0-9]{1,})#/i))
            {
                var makeid=tmpValue.substr(0,tmpValue.indexOf('#'));
                var make=tmpValue.substr(tmpValue.indexOf('#')+1,tmpValue.length);

                arrModel=(m[makeid]).split(',');

                for(i=0; i < arrModel.length; i++)
                {
                    var model_value=new String(arrModel[i]);

                    for(h=0; h<tot; h++)
                    {
                        var v2Value=v2.options[h].value;

                        if(v2Value == model_value)
                        {
                            var j=0;

                            for(var r=h; r<tot;r++)
                            {
                                j=r+1;

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

                                var disp=v2.options[j].text;
                                var val=v2.options[j].value;

                                selOpt=new Option(disp,val);
                                eval('v2.options[r]=selOpt');
                            }
                            v2.length=tot-1;
                            tot=v2.length;
                        }
                    }
                }
            }
        }

        if(dup != 1)
        {
            if((v1.id_model[v1.id_model.selectedIndex].value).match(/^([0-9]{1,})#/i) )
                selOpt=new Option(v1.id_model[v1.id_model.selectedIndex].text,v1.id_model[v1.id_model.selectedIndex].value);
            else
            {
                str1=v1.id_model[0].text; // Get the name of Vehicle Make from string.
                selOpt=new Option(str1.slice(0,str1.indexOf(':'))+'-'+v1.id_model[v1.id_model.selectedIndex].text,v1.id_model[v1.id_model.selectedIndex].value);
            }
            eval('v2.options[tot]=selOpt');
        }
    }
}

//Function to add selected values from 'Part Categort' fields
//into 'Selected Part Category' field, used in Advanced search page
function addPartCategory(v1,v2,v3)
{
    if(!(v1.id_part_category.selectedIndex >= 0))
        return;

    if(v1.id_part_category[v1.id_part_category.selectedIndex].value != '')
    {
        if (v2.length > 0)
        {
            if(v2.options[0].value == '')
                document.adv.id_sel_part_category.length--;
        }

        if(v2.selectedIndex == 1)
            v2.selectedIndex=0;

        tot=v2.length;
        dup=0;

        if(v3.selectedIndex == '' || v3.selectedIndex <= 0)
            selPartId='';
        else
            selPartId=v1.id_part_type[v1.id_part_type.selectedIndex].value;

        if (selPartId > 0 || selPartId != '')
            pType=partType[selPartId];
        else
            pType='';

        for(o=0; o<tot; o++)
        {
            var tmpValue2=v2.options[o].value;
            var tmpValue=v1.id_part_category[v1.id_part_category.selectedIndex].value;

            if(tmpValue == tmpValue2)
            {
                dup=1;
                alert(msgDupCatSelected);
            }
            else if(tmpValue.match(/^([0-9]{1,})$/i) && tmpValue2.match(/^([0-9]{1,})#/i))
            {
                makeid=tmpValue2.substr(0,tmpValue2.indexOf('#'));
                make=tmpValue2.substr(tmpValue2.indexOf('#')+1,tmpValue2.length);

                for(i=0; i < pId[makeid].length; i++)
                {
                    model_value=new String(pId[makeid][i]);

                    if(tmpValue == model_value)
                    {
                        dup=1;
                        alert(catAllSelected);
                    }
                }
            }
            else if(tmpValue.match(/^([0-9]{1,})#/i))
            {
                makeid=tmpValue.substr(0,tmpValue.indexOf('#'));
                make=tmpValue.substr(tmpValue.indexOf('#')+1,tmpValue.length);

                for(i=0; i < pId[makeid].length; i++)
                {
                    model_value=new String(pId[makeid][i]);

                    for(h=0; h<tot; h++)
                    {
                        var v2Value=v2.options[h].value;

                        if(v2Value == model_value)
                        {
                            j=0;

                            for(var r=h; r<tot;r++)
                            {
                                j=r+1;

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

                                if (pType != '')
                                    disp=pType+'-'+v2.options[j].text;
                                else
                                    disp=v2.options[j].text;
                                val=v2.options[j].value;

                                selOpt=new Option(disp,val);
                                eval('v2.options[r]=selOpt');
                            }
                            v2.length=tot-1;
                            tot=v2.length;
                        }
                    }
                }
            }
        }

        if(dup != 1)
        {
            if(pType != '')
                selOpt=new Option(pType+'-'+v1.id_part_category[v1.id_part_category.selectedIndex].text,v1.id_part_category[v1.id_part_category.selectedIndex].value);
            else
                selOpt=new Option(v1.id_part_category[v1.id_part_category.selectedIndex].text,v1.id_part_category[v1.id_part_category.selectedIndex].value);

            eval('v2.options[tot]=selOpt');
        }
    }
}

function removePartCategory(v1)
{
    p=v1.id_sel_part_category.selectedIndex;
    j=0;
    tot=v1.id_sel_part_category.options.length;

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

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

            disp=v1.id_sel_part_category[j].text;
            val=v1.id_sel_part_category[j].value;

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

    //If no option is there then add "any" as default
    if(v1.id_sel_part_category.options.length == 0)
    {
        selOpt=new Option('                                                      ','');
        eval("v1.id_sel_part_category.options[0]=selOpt");
    }
}

function removeModel(v1)
{
    p=v1.id_sel_model.selectedIndex;
    j=0;
    tot=v1.id_sel_model.options.length;

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

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

            disp=v1.id_sel_model[j].text;
            val=v1.id_sel_model[j].value;

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

    //If no option is there then add "any" as default
    if(v1.id_sel_model.options.length == 0)
    {
        selOpt=new Option('                                                      ','');
        eval("v1.id_sel_model.options[0]=selOpt");
    }
}

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

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

    if(curval=='' && v2.selectedIndex > 0)
        curval=v2.options[v2.selectedIndex].value;

    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 the Price list box options
function PriceChange(v1,v2,curval,sign)
{
    if(v1.selectedIndex < 1)
        st=1;
    else
        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+" "+sign;
        }
        else
            var 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=no,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 suhmit favorite page by adding/removing cottages
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] + ')';

                if(arr[1] != '0')
                {
                    idiv('common_messageX').innerHTML = arr[1] + ' ' + msgAddFav;
                    idiv('Add_To_Fav_End').innerHTML  = arr[1] + ' ' + msgAddFav;
                }
                else
                {
                    idiv('common_messageX').innerHTML = msgRptAddFav;
                    idiv('Add_To_Fav_End').innerHTML  = msgRptAddFav;
                }
                idiv('common_messageX').style.display = 'block';
                idiv('Add_To_Fav_End').style.display = 'block';
                idiv('loadingImg').style.display='none';
                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();
    }
}

function removeRec(ml,act,frm,checkname,msg)
{
    var count = 0;
    var len = ml.elements.length;
    var checkNameLength=checkname.length;
    for (var i = 0; i < len; i++)
    {
        var e = ml.elements[i];
        if ((e.name.substr(0,checkNameLength) == checkname) && e.checked == true)
        {
            count++;
        }
    }

    if (count == 0)
    {
        alert(msg);
        return false;
    }
    else
    {
        confirmMultiDel(act,frm);
    }
}

//To check login sesion of user in VIF while sumbitting
//question or giving answer, if user is not logged in
//a popup 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","na_login");
        else
            openImg("popUpLogin.php?M=OnlyForRegisteredUser","350","320","na_login");

        return false;
    }
    var flag="N";

    for(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(msgBlankForm);
        return false;
    }
}
//Function to return nothing, this is used sometimes
//to display tool tip on plain text by making trick
function returnVoid() {}

/** Removing option group */
function RemoveGroups(selectId,v2,make_txt)
{
    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 confirmReset(thisForm)
{
    if(confirm(msgConfirmReset))
        return true;

    return false;
}

// 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 < c.length; i++)
            {
                if(sCnt[idCat][i] > 0)
                {
                    if(sAvail[idCat][i].match(/NP/))
                    {
                        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";
        }
    }
}

function sd_ajaxQue(formObj,var_O)
{
    if(checkQue(formObj,var_O) != false )
    {

        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',_su+'/simple_dealer/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);
                document.getElementById('loaderimg').style.display='none';
            }
        }
        xmlHttpReq.send(null);
        return false;
    }
    else
        return false;
}

function sd_ajaxLoadImage(id)
{
    var qa_id = id;

    if(document.getElementById('np_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',_su+'/simple_dealer/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;
}

//      Fn. for Login modal
function loginmodal(opt,rPage)
{
    //  D => Simple Dealer , N => From View Page , P => Post Ad, RP => any given redirect page rPage
    var pageURL = '';
    if(opt == "D")
    {
        pageURL = "../modalLogin.php?mainOnly=1&sd=1";
        idiv('lightbox').style.left = "65%";
    }
    else if(opt == "N")
    {
        pageURL = "modalLogin.php?mainOnly=1&sd=0";
        idiv('lightbox').style.left = "40%";
//      idiv('lightbox').style.left = "50%";
    }
    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_modal").blur();

    if(opt == "D")
        pageURL = "../modalLogin.php?mainOnly=1&sd=1";
    else if(opt == "N")
        pageURL = "modalLogin.php?mainOnly=1&sd=0";
    else if(opt == "P")
        pageURL = "modalLogin.php?mainOnly=1&postad=1";

    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="home.php";
                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(isblank(document.sendlink.userEmail.value))
    {
        alert(msgMandet);
        document.sendlink.userEmail.focus();
        return false;
    }
    else 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_part='+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 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=NP';
   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);
   }
   else if(frmObj.name == 'rimAdv')
   {
       return ajaxCounterChng(ajaxFName+'&frm=RIMADV&'+ 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';
    else if(frmName == 'rimAdv')
        loadingImg='loadingImg_src_chngCntRimTyreAdv';

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

    var xmlHttpReq=createXHR();

    xmlHttpReq.open('GET',ajaxFname,true);
    xmlHttpReq.setRequestHeader("Content-Type", "text/xml;charset=UTF-8");
    xmlHttpReq.onreadystatechange=function() {
        if(xmlHttpReq.readyState == 4) {
            showResponse(xmlHttpReq.responseXML);
            idiv(loadingImg).style.display='none';
        }
    }
    xmlHttpReq.send(null);
    return false;
}
/** This function is return whole url with append of selected search criteria*/
function cleanFrmUrl(qs)
{
   var len =qs.elements.length;
   var u='';

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

   for(var i = 0; i < len; 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;
}