/** Define global variable for those field they generated using javascript, used for manipulation */
var partCat=new Array();
var mkModel=new Array();
var selTown=new Array();
var yrTo='';
var rimSizeTo='';

/** This function call from 'setDefReset' function to set the default value of given form field name
var advFormField : this contain the HTMLobject i.e. document.formName.fieldname
*/
function setDefValue(advFormField)
{
    if(advFormField && advFormField.length > 0)
    {
        var defValArr=new Array();

        for(var i=0; i<advFormField.length; i++)
        {
            /** Assign value and text name seperated with ,to defValArr array of given field name */
            if(advFormField[i].value != "")
                defValArr[i]=advFormField[i].value+","+advFormField[i].text;
        }
        return defValArr;
    }
}

/** when page is loaded store default value of those field they generated using javaScript,
    this field value is not reset using reset function of javascript so, reset manually.
*/
function setDefReset(advForm)
{
    /** Set values for 'No upper limit' comboboxes */
    if(advForm.yearTo.selectedIndex > 0)
        yrTo=advForm.yearTo.value;

    /** Set values for 'No upper limit' comboboxes */
    if(advForm.id_rims_size_to.selectedIndex > 0)
        rimSizeTo=advForm.id_rims_size_to.value;

    /** Set for selected filed area  */
    if(advForm.id_sel_part_category.length > 0)
        partCat=setDefValue(advForm.id_sel_part_category);

    if(advForm.id_sel_model.length > 0)
        mkModel=setDefValue(advForm.id_sel_model);

	if(advForm.id_sel_town.length > 0)
		selTown=setDefValue(advForm.id_sel_town);
}
function blankFa()
{
	if(!isblank(document.getElementById('findAgent').value))
	{
		if(!(document.getElementById('findAgent').value.match(/^[0-9a-zA-ZåÅäÄöÖÁÀÉÈÒÓÙÚáàèéòóùúÝìíýÌÍ_´:\s\,-]{1,20}$/)))
		{
			alert(msgInvalidFa);
			document.getElementById('findAgent').focus();
			return false;
		}
	}
	else
	{
		alert(msgInvalidFa);
		document.getElementById('findAgent').focus();
		return false;
	}
	return true;
}
function searchFA()
{
	if(document.getElementById('findAgent').value.length > 0)
	{
		alert(msgFaForRegUser);
		document.getElementById('findAgent').value='';
		document.getElementById('findAgent').focus();
		return false;
	}
}
/**
Function to assign the values of the listboxes to the hidden variables.
The values will be enclosed by ' separated with ,
*/
function checkFa()
{
    var p="";
	var z="";
	var cg="";
	var t="";

    if(!isblank(document.adv.adv_make.value))
    {
        if(!(document.adv.adv_make.value.match(/^[0-9a-zA-ZåÅäÄöÖÁÀÉÈÒÓÙÚáàèéòóùúÝìíýÌÍ_´:\s\,-]{1,250}$/)))
        {
            alert(msgMake);
            document.adv.adv_make.focus();
            return false;
        }
    }

    if(!isblank(document.adv.adv_model.value))
    {
        if(!(document.adv.adv_model.value.match(/^[0-9a-zA-ZåÅäÄöÖÁÀÉÈÒÓÙÚáàèéòóùúÝìíýÌÍ_:´()\s\+\,"'.-]{1,250}$/)))
        {
            alert(msgModel);
            document.adv.adv_model.focus();
            return false;
        }
    }

    if(document.adv.id_sel_model.length > 0)
    {
        for(a=0; a<document.adv.id_sel_model.length-1; a++)
        {
            if(document.adv.id_sel_model[a].value != "")
                p += "'"+document.adv.id_sel_model[a].value+"',";
        }
        if(document.adv.id_sel_model[a].value != "")
            p += "'"+document.adv.id_sel_model[a].value+"'";
        document.adv.zModel.value=p;
    }
    if(document.adv.id_sel_part_category.length > 0)
    {
        for(a=0; a<document.adv.id_sel_part_category.length-1; a++)
        {
            if(document.adv.id_sel_part_category[a].value != "")
                cg += "'"+document.adv.id_sel_part_category[a].value+"',";
        }
        if(document.adv.id_sel_part_category[a].value != "")
            cg += "'"+document.adv.id_sel_part_category[a].value+"'";
        document.adv.zPartCategory.value=cg;
    }
	if(document.adv.id_sel_town.length > 0)
    {
        for(a=0; a<document.adv.id_sel_town.length-1; a++)
        {
            if(document.adv.id_sel_town[a].value != "")
                t += document.adv.id_sel_town[a].value+",";
        }
        if(document.adv.id_sel_town[a].value != "")
            t += document.adv.id_sel_town[a].value;

        document.adv.selTown.value=t;
    }
    return true;
}

function addAny(v1,v2)
{
    if(v1.options.length == 0)
    {
        selOpt=new Option("                                                       ","");
        eval("v1.options[0]=selOpt");
    }
    if(v2.options.length == 0)
    {
        selOpt=new Option("                                          ","");
        eval("v2.options[0]=selOpt");
    }
}
function chkMandOutOfTwo(chk,chkOther)
{
    //if another checkbox is not selected/checked, keep the first one as selected regardless of
    //whether user has checked or unchecked.
    if(!chkOther.checked)
        chk.checked=true;

    return;
}

//Function to change the Length,Power and Price list box options
function listboxChange(v1,v2,curval)
{
    var st,len,disp,disp1,disp2,i,j,tot,temp;
    if(v1.selectedIndex < 1)
        st=1;
    else
        st=v1.selectedIndex;

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

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

    for(i=st,j=1; i < tot;i++,j++)
    {
        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;
        }
        else
            disp=v1.options[i].value;

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

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

function loadDef(v1)
{
    if(!v1.value)
    {
        if(v1.name=='priceFrom')
 	       v1.value=lvalue;
        else
            v1.value=uvalue;
    }
}

//Function to change the rims entity list box options
function rimEntityChange(v1,v2,curval)
{
    var st,len,disp,disp1,disp2,i,j,tot,temp;
    if(v1.selectedIndex < 1)
        st=1;
    else
        st=v1.selectedIndex;

    if(!curval && v2.selectedIndex > 0)
        curval=v2.options[v2.selectedIndex].text;

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

    for(i=st,j=1; i < tot;i++,j++)
    {
        disp=v1.options[i].text;

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

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

function ajaxListChange(frmObj,chgFor,efs)
{
    var efs,idad,pars;
    var xhr=createXHR();

    pars=Form.serialize($(frmObj));
    if(typeof efs == 'undefined') efs='';

    pars +='&site=NP&chgFor=' + chgFor + '&ajxr=A' + efs + '&frm=' + frmObj.name;

    xhr.open('POST',_su+'/ajaxChangeEntity.php');
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-length", pars.length);
    xhr.setRequestHeader("Connection", "close");
    xhr.onreadystatechange=function()
    {
        if(xhr.readyState == 4)
        {
            showTextResponse(xhr.responseText);

            if(frmObj.name == 'partpost' && (!chgFor || chgFor == 'PT'))
            {
                AddRemoveRimsBoltInfo(frmObj.part_type);
                hideShowExtraField(frmObj.partpost_id_part_type.value);
                hideShowVehicleModel(frmObj.vehicle_type.value);
                hideShowPartModel(frmObj.part_type.value);
            }

            if(frmObj.name == 'srch' || frmObj.name == 'adv')
            {
                if(frmObj.name == 'adv')
                    partCatChange(frmObj.id_part_type);
                callAjax(frmObj);
            }
        }
    }
    xhr.send(pars);
    return false;
}

function addModel(v1)
{
    var md=v1.id_model;
    var arrModel=new Array();
    var v2=v1.id_sel_model

    if(!(md.selectedIndex >= 0))
        return;

    if(md[md.selectedIndex].value != '')
    {
        if(v2.options[0].value == '')
            v2.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=md[md.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=arrkeepmodel[makeid];

                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);

                for(i=1; i < md.length; i++)
                    arrModel[i]=md[i].value;

                arrkeepmodel[makeid]=arrModel;

                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((md[md.selectedIndex].value).match(/^([0-9]{1,})#/i) )
                selOpt=new Option(md[md.selectedIndex].text,md[md.selectedIndex].value);
            else
            {
                str1=md[0].text; // Get the name of Vehicle Make from string.
                selOpt=new Option(str1.slice(0,str1.indexOf(':'))+'-'+md[md.selectedIndex].text,md[md.selectedIndex].value);
            }
            eval('v2.options[tot]=selOpt');
        }
    }
}
function addPartCategory(v1)
{
    var spc=v1.id_sel_part_category;
    var pt=v1.id_part_type;
    var pc=v1.id_part_category;

    if(!(pc.selectedIndex >= 0))
        return;

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

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

        tot=spc.length;
        dup=0;

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

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

            if(tmpValue == tmpValue2)
            {
                dup=1;
                alert(msgDupCatSelected);
            }
        }

        if(dup != 1)
        {
            selOpt=new Option(pt[pt.selectedIndex].text + ' -'+pc[pc.selectedIndex].text,pc[pc.selectedIndex].value);
            eval('spc.options[tot]=selOpt');
        }
    }
}
function removePartCategory(v1)
{
    p=v1.id_sel_part_category.selectedIndex;
    tot=v1.id_sel_part_category.options.length;
    j=0;

    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(tot == 0)
    {
        selOpt=new Option('','');
        eval("v1.id_sel_part_category.options[0]=selOpt");
    }
}

function callAjax(frmObj)
{
    var loadingImg = value ='';   
   /** 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();
       value ='&frm=ADV&';
    }
    else if(frmObj.name == 'srch')          
       value ='&frm=SIMP&';   
    else if(frmObj.name == 'rimAdv')   
        value ='&frm=RIMADV&';   

    var searchUrl = ajaxFName+value+ cleanFrmUrl(frmObj);   
    var ajaxFname=searchUrl.replace('/#/ig','@');
    
    if(frmObj.name == 'adv')
        loadingImg='loadingImg_src_chngCntAdv';
    else if(frmObj.name == 'srch')
        loadingImg='loadingImg_src_chngCnt';
    else if(frmObj.name == 'rimAdv')
        loadingImg='loadingImg_src_chngCntRimTyreAdv';
    
    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).style.display='none';
        }
    };
    xmlHttpReq.send(null);
    return false;  
}
function getDomTown(domVal,curval,page)
{
    var townStr='';
    var townUrl=_su + '/ajaxGetDomicileTown.php?ajxifrm=A&frm='+page+'&site=NP&';

    if(curval) townStr='&sel_id_town='+curval;    

    if(page == 'ADV')
        AjaxUpdater('adv_id_town',townUrl+'id_domicile='+domVal+townStr,"callAjax(document.adv);");
    else if(page == 'SIMP')
        AjaxUpdater('srch_id_town',townUrl+'id_domicile='+domVal+townStr,"callAjax(document.srch);");
    else if(page == 'POST')
        AjaxUpdater('post_id_town',townUrl+'id_domicile='+domVal+townStr);
    else if(page == 'listService')
        AjaxUpdater('service_id_town',townUrl+'id_domicile='+domVal+townStr);
}
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 hideShowSearch(divId)
{
    if(divId == 'rim_search') //  Display Rim search div and unset values of tyre/tyre set div
    {
        document.getElementById('rim_search').style.display='block';
        document.getElementById('tyre_search').style.display='none';

        document.getElementById('adv_make').style.display='';
        document.getElementById('id_rim_category').style.display='';
        document.getElementById('id_rims_size').style.display='';
        document.getElementById('id_condition').style.display='';

        document.getElementById('section1').style.display='none';
        document.getElementById('section2').style.display='none';
        document.getElementById('section3').style.display='none';

        document.getElementById('id_tyre_inch').style.display='none';
        document.getElementById('id_tyre_category').style.display='none';
        document.getElementById('id_tyre_set_category').style.display='none';
        document.getElementById('rims_make').style.display='none';

        document.rimAdv.rims_make.value='';
        document.rimAdv.id_tyre_inch_fr.value='';
        document.rimAdv.id_tyre_inch_to.value='';
        document.rimAdv.id_tyre_category.value='';
        document.rimAdv.id_tyre_set_category.value='';
        document.rimAdv.id_tyre_manufacturer.value='';
        document.rimAdv.id_tyre_width_fr.value='';
        document.rimAdv.id_tyre_width_to.value='';
        document.rimAdv.id_tyre_profile_fr.value='';
        document.rimAdv.id_tyre_profile_to.value='';
        document.rimAdv.id_tyre_speed_limit.value='';
        document.rimAdv.c_tyre.checked=false;
    }
    else if(divId == 'tyre_search') //  Display tyre/tyre set search div and unset values of rim div
    {
        document.getElementById('tyre_search').style.display='block';

        if(document.getElementById('part_type_3').checked)
        {
            document.getElementById('id_tyre_category').style.display='';
            document.getElementById('id_tyre_set_category').style.display='none';
            document.getElementById('rims_make').style.display='none';

            document.rimAdv.id_tyre_set_category.value='';
            document.rimAdv.rims_make.value='';

            document.getElementById('rim_search').style.display='none';
            document.getElementById('id_bolt_pattern').value='';
            document.getElementById('id_rims_offset_fr').value='';
            document.getElementById('id_rims_offset_to').value='';
            document.getElementById('id_rims_width_fr').value='';
            document.getElementById('id_rims_width_to').value='';
            document.getElementById('id_rims_diameter').value='';

            document.getElementById('section1').style.display='none';
            document.getElementById('section2').style.display='none';
            document.getElementById('section3').style.display='none';
        }
        else if(document.getElementById('part_type_4').checked)
        {
            document.getElementById('rim_search').style.display='block';
            document.getElementById('section1').style.display='block';
            document.getElementById('section2').style.display='block';
            document.getElementById('section3').style.display='block';

            document.getElementById('id_tyre_category').style.display='none';
            document.getElementById('id_tyre_set_category').style.display='';
            document.getElementById('rims_make').style.display='';
            document.rimAdv.id_tyre_category.value='';
        }

        document.getElementById('id_tyre_inch').style.display='';

        document.getElementById('adv_make').style.display='none';
        document.getElementById('id_rim_category').style.display='none';
        document.getElementById('id_rims_size').style.display='none';
        document.getElementById('id_condition').style.display='none';

        document.rimAdv.adv_make.value='';
        document.rimAdv.id_rim_category.value='';
        document.rimAdv.id_rims_size_fr.value='';
        document.rimAdv.id_rims_size_to.value='';
        document.rimAdv.id_rims_condition.value='';
    }
}
function resetFormAdvSrch(advForm)
{
    advForm.reset();

    advForm.yearTo.value=yrTo;
    yearChange(advForm.yearFrom,advForm.yearTo,V_YEAR_TO);
    rimEntityChange(advForm.id_rims_size_fr,advForm.id_rims_size_to,RIMS_SIZE_LIST_TO);
    rimEntityChange(advForm.id_tyre_inch_fr,advForm.id_tyre_inch_to,TYRE_INCH_SIZE_LIST_TO);

    if(partCat)
    {
        /** Remove all value of the part category */
        advForm.id_part_category.options.length=0;
        selOpt=new Option('','');
        eval("advForm.id_part_category.options[0]=selOpt");

        /** Get the default value of selected part category */
        getDefValue(advForm.id_sel_part_category,partCat,'');
    }

    if(mkModel)
    {
        /** Get the default value of selected make and model */
        getDefValue(advForm.id_sel_model,mkModel,'');
    }
    ajaxListChange(document.forms.adv,'',efs);

    document.getElementById('rims_make').style.display='none';
    document.getElementById('rims_make').text='';
    document.getElementById('tyre_manufacturer').style.display='none';
    document.getElementById('id_tyre_manufacturer').value='';

    if(selTown)
        getDefValue(advForm.id_sel_town,selTown,'');

    if(advForm.id_domicile)
        getDomTown(advForm.id_domicile.value,'','ADV');// Default counter will call from here
    else
        callAjax(document.adv);

    return true;
}

function partCatChange(ptype)
{
    if(ptype.value == '24' || ptype.value == '38')
    {
        document.getElementById('tyre_manufacturer').style.display='';
        document.getElementById('inch_size').style.display='';
        document.getElementById('rims_size').style.display='none';
        document.getElementById('id_rims_size_fr').value='';
        document.getElementById('id_rims_size_to').value='';
    }
    else
    {
        document.getElementById('tyre_manufacturer').style.display='none';
        document.getElementById('id_tyre_manufacturer').value='';
        document.getElementById('inch_size').style.display='none';
        document.getElementById('rims_size').style.display='';
        document.getElementById('id_tyre_inch_fr').value='';
        document.getElementById('id_tyre_inch_to').value='';
    }

    if(ptype.value == '38')
        document.getElementById('rims_make').style.display='';
    else
    {
        document.getElementById('rims_make').style.display='none';
        document.getElementById('rims_make').text='';
    }
}
function resetFormRimsAdvSrch(advForm)
{
    advForm.reset();

    rimEntityChange(advForm.id_rims_size_fr,advForm.id_rims_size_to,RIMS_SIZE_LIST_TO);
    rimEntityChange(advForm.id_rims_offset_fr,advForm.id_rims_offset_to,RIMS_OFFSET_LIST_TO);
    rimEntityChange(advForm.id_rims_width_fr,advForm.id_rims_width_to,RIMS_WIDTH_LIST_TO);
    rimEntityChange(advForm.id_rims_size_fr,advForm.id_rims_size_to,RIMS_SIZE_LIST_TO);

    rimEntityChange(advForm.id_tyre_inch_fr,advForm.id_tyre_inch_to,TYRE_INCH_SIZE_LIST_TO);
    rimEntityChange(advForm.id_tyre_width_fr,advForm.id_tyre_width_to,TYRE_WIDTH_LIST_TO);
    rimEntityChange(advForm.id_tyre_profile_fr,advForm.id_tyre_profile_to,TYRE_PROFILE_LIST_TO);

    document.getElementById('part_type_2').checked=true;
    hideShowSearch('rim_search');
    callAjax(document.rimAdv);
    return true;
}
