/* $Id: nf_common.js,v 1.38 2010/02/17 09:19:19 riddhi Exp $ */

var _su='http://'+location.hostname;
var textSearch = '{C_FREE_SEARCH}';

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 loadDefault(v1)
{
    if(!v1.value)
    {
        v1.value=textSearch;
    }
}

function check_search()
{
    var lre,rre;

    if(document.search.item_id.value == '')
    {
        /** Why both have value */
        alert(msgEnterOne);
        document.search.item_id.focus();
        return false;
    }
    else
    {
        /** If item id is there */
        if(document.search.item_id.value)
        {
            if(document.search.item_id.value.match(/^[0-9]{1,}$/))
            {
                //Strips blank spaces from left and right
                lre=/^\s*/;
                rre=/\s*$/;

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

                self.location.replace("listQuickSearchItem.php?q="+document.search.item_id.value+"&quick_search_id="+document.search.quick_search_id.value+"&fws="+document.search.quick_search_id.value);
            }
            else
            {
                alert(msgNumeric);
                document.search.item_id.select();
                document.search.item_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|listItem|listAdvSearchFindAgent|listCategory)/)){
        document.cookie = 'scroll=' +page+ document.documentElement.scrollTop
                        + "; expires="+ date.toGMTString();
    }
    if(page.match(/^viewItem/)){
        document.cookie = "prevpage="+page + "; expires="+ date.toGMTString();
    }
}
function maintainScrollLoad()
{
    var page=getPage();
    if( document.cookie.match(/prevpage=viewItemphp/ ) )
    {
        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 ad_loginmodal(opt,rPage)
{
    if(opt == 'N')
    {
        pageURL = _su+'/modalLogin.php?mainOnly=1&sd=0';
        idiv('lightbox').style.left = '40%';
    }
    else if(opt == 'P')
    {
        pageURL = _su+'/modalLogin.php?mainOnly=1&postad=1';
        idiv('lightbox').style.left = '40%';
    }
	else if(opt == 'RP')
	{
	    pageURL = _su+'/modalLogin.php?mainOnly=1&redirectPage='+rPage;
        idiv('lightbox').style.left = '40%';
	}

    lightbox.prototype.content = pageURL;
    lightbox.prototype.activate();
    idiv('lightbox').style.top = '60%';
    idiv('lightbox').style.width = '295px';
}
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);
}
//changeCategory(reference_type,reference_category)
function changeCategory(itemTypeList,itemCatList,currVal,capAny)//,curval_more,cond,extra)
{
  	var catOpt,selAny=true;

  	removeOpt(itemCatList);

	//Getting selected item type
	id_item_type=itemTypeList.value;

	//Fill the list box with categories of the selected item type
	if(icati[id_item_type])
	{
		var i=0;
		while(icati[id_item_type][i])
		{
			//Create new option and add that option to the category list box
			if(navigator.userAgent.match(/IE/))
			{
				catOpt = document.createElement('Option');

				catOpt.value=icati[id_item_type][i];
				catOpt.innerText=icatn[id_item_type][i];

				if(currVal == icati[id_item_type][i])
				{
					  catOpt.selected = true;
					  selAny = false;
				}

				itemCatList.appendChild(catOpt);
			}
			else
			{
				catOpt= new Option(icatn[id_item_type][i],icati[id_item_type][i]);

				if(currVal == icati[id_item_type][i])
				{
					catOpt.selected = true;
					selAny = false;
				}

				itemCatList.options.add(catOpt);
			}

			i++;
		}
	}

	if(selAny)
		itemCatList.options[0].selected = true;
}

function changeSection(itemTypeList,itemCatList,itemSecList,currVal,capAny)
{
	var catOpt,selAny=true;

  	removeOpt(itemSecList);

	id_item_type=itemTypeList.value;
	id_item_cat=itemCatList.value;

	//Fill the list box with categories of the selected item type

	if(id_item_type > 0)
	{
		if(iseci[id_item_type][id_item_cat])
		{
			var i=0;
			while(iseci[id_item_type][id_item_cat][i])
			{
				//Create new option and add that option to the category list box
				if(navigator.userAgent.match(/IE/))
				{
					opt = document.createElement('Option');

					opt.value=iseci[id_item_type][id_item_cat][i];
					opt.innerText=isecn[id_item_type][id_item_cat][i];

					if(currVal.match(iseci[id_item_type][id_item_cat][i]))
					{
						opt.selected = true;
						selAny = false;
					}

					itemSecList.appendChild(opt);
				}
				else
				{
					opt= new Option(isecn[id_item_type][id_item_cat][i],iseci[id_item_type][id_item_cat][i]);

					if(currVal.match(iseci[id_item_type][id_item_cat][i]))
					{
						opt.selected = true;
						selAny = false;
					}

					itemSecList.options.add(opt);
				}

				i++;
			}
		}
	}

	if(selAny)
		itemSecList.options[0].selected = true;
}

/* newly  added function starts here */
function getCategory(itemTypeList,itemCatList,currVal)
{
	var catOpt;

	//Remove all categories from the list except the first entry
	if(itemCatList.options.length > 0)
	{
		itemCatList.options.length=1;
		itemCatList.options[0].selected=true;
	}

	//Getting selected item type
	id_item_type=itemTypeList.value;

	//Fill the list box with categories of the selected item type
	if(s_icati[id_item_type])
	{
		var i=0;
		while(s_icati[id_item_type][i])
		{
			//Create new option and add that option to the category list box
			if(navigator.userAgent.match(/IE/))
			{
				catOpt = document.createElement('Option');

				catOpt.value=s_icati[id_item_type][i];
				catOpt.innerText=s_icatn[id_item_type][i];

				if(currVal == s_icati[id_item_type][i])
					  catOpt.selected = true;

				itemCatList.appendChild(catOpt);
			}
			else
			{
				catOpt= new Option(s_icatn[id_item_type][i],s_icati[id_item_type][i]);

				if(currVal == s_icati[id_item_type][i])
					catOpt.selected = true;

				itemCatList.options.add(catOpt);
			}

			i++;
		}
	}
}

function getSection(itemTypeList,itemCatList,itemSecList,currVal)
{
	var opt;

	//Remove all categories from the list except the first entry
	if(itemSecList.options.length > 0)
	{
		itemSecList.options.length=1;
		itemSecList.options[0].selected=true;
	}

	//Getting selected item type
	id_item_type=itemTypeList.value

	//Getting selected item category
	id_item_cat=itemCatList.value;

	//Fill the list box with categories of the selected item type
	if(id_item_type > 0)
	{
		if(s_iseci[id_item_type][id_item_cat])
		{
			var i=0;
			while(s_iseci[id_item_type][id_item_cat][i])
			{
				//Create new option and add that option to the category list box
				if(navigator.userAgent.match(/IE/))
				{
					opt = document.createElement('Option');

					opt.value=s_iseci[id_item_type][id_item_cat][i];
					opt.innerText=s_isecn[id_item_type][id_item_cat][i];

					if(currVal == s_iseci[id_item_type][id_item_cat][i])
						opt.selected = true;

					itemSecList.appendChild(opt);
				}
				else
				{
					opt= new Option(s_isecn[id_item_type][id_item_cat][i],s_iseci[id_item_type][id_item_cat][i]);

					if(currVal == s_iseci[id_item_type][id_item_cat][i])
						opt.selected = true;

					itemSecList.options.add(opt);
				}

				i++;
			}
		}
	}
}

function getType(itemTypeList,currVal)
{
	var i=0;
	while(s_itypi[i])
	{
		//Create new option and add that option to the category list box
		if(navigator.userAgent.match(/IE/))
		{
			catOpt = document.createElement('Option');

			catOpt.value=s_itypi[i];
			catOpt.innerText=s_itypn[i];

			if(currVal == s_itypi[i])
					catOpt.selected = true;

			itemTypeList.appendChild(catOpt);
		}
		else
		{
			catOpt= new Option(s_itypn[i],s_itypi[i]);

			if(currVal == s_itypi[i])
				catOpt.selected = true;

			itemTypeList.options.add(catOpt);
		}

		i++;
	}
}

function removeOpt(listbox)
{
	if(listbox.options.length > 0)
	{
		listbox.options.length=1;
		//listbox.options[0].selected=true;
	}
}

function changeTown(domicileList,townList,currVal,capAny,siteBranch)
{
	var i,id_domicile = domicileList.value,selAny=true;

	removeOpt(townList);

	if(t[id_domicile])
	{
		i=0;

        /** Puts 'All' caption in case the browser is IE */
        if(navigator.userAgent.match(/IE/) && siteBranch != 'NF')
            townList.options[0].text=capAll;

		while(t[id_domicile][i])
		{
			if(navigator.userAgent.match(/IE/))
			{
				opt = document.createElement('Option');

				opt.value=t[id_domicile][i];
                opt.innerText=n[id_domicile][i];

				if(currVal.match(t[id_domicile][i]))
				{
					opt.selected = true;
					selAny = false;
				}

				townList.appendChild(opt);
			}
			else
			{
				if(siteBranch != 'NF')
					townList.options[0] = new Option(capAll);

				opt= new Option(n[id_domicile][i],t[id_domicile][i]);

				if(currVal.match(t[id_domicile][i]))
				{
					opt.selected = true;
					selAny = false;
				}

				townList.options.add(opt);
			}
			i++;
		}
        if(selAny)
            townList.options[0].selected = true;
	}
    else
    {
        /** if id_domicile not selected in simple search. */
        if(capAny == 'Y')
        {
            townList.length=1;
            var j=1;
            var bflag=1;

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

			if(siteBranch != 'NF')
				townList.options[0] = new Option(capAll);

            for(dm=0; dm < di.length; dm++)
            {
                if(!dn[di[dm]] || di[dm] == 15)
                    continue;

                var domicile_text=new String(dn[di[dm]]);

                if(domicile_text != '')
                {
                    if(!navigator.userAgent.match(/Opera/) && bflag == 1)
                    {
                        optGroup='T';
                        textureGroup=document.createElement ('optgroup');
                        textureGroup.label=domicile_text;
                        townList.appendChild(textureGroup);
                    }
                    else
                        optGroup='F';

                    for(tw=0; tw < t[di[dm]].length; tw++)
                    {
                        var town_value=new String(t[di[dm]][tw]);
                        var town_text=new String(n[di[dm]][tw]);

                        if(optGroup != 'F' && domicile_text != '')
                        {
                            town_opt=document.createElement('option');
                            town_opt.value=town_value;

                            if(navigator.userAgent.match(/IE/))
                                town_opt.innerText=town_text;
                            else
                                town_opt.text=town_text;

                            textureGroup.appendChild(town_opt);
                        }
                        else
                        {
                            townOpt=new Option(town_text,town_value);
                            townList.options.add(townOpt);
                        }
                        /** OPTION GROUP PART ENDS HERE */

                        /** Display the selected values. */
                        if(currVal.search("'"+t[di[dm]][tw]+"'") != -1)
                            townList.options[j].selected=true;

                        if(t[di[dm]][tw] == currVal)
                            townList.options[j].selected=true;

                        j++;
                    }
                }
            }
        }
    }
}

//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(item 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 remove the domicile wise optGroups in simple search. */
function RemoveGroups(selectId)
{
    for(var chr=0; chr < di.length; chr++)
    {
        if(!dn[di[chr]] || di[chr] == 15)
            continue;

        RemoveGroup(dn[di[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 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=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(_su+"/msgWin.php?opt="+msgVar,width,height,'newuser');
}

//Function to submit favorite page by adding/removing items
function submitFav(thisV,siteCode)
{
	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(siteCode == 'NF')
                        idiv('favorite_cnt_end').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('loadingImg').style.display ='none';
                idiv('Add_To_Fav_End').style.display='block';
                idiv('loadingImg2').style.display='none';
            }
        }
        xmlHttpReq.send(pars);
        return false;

		//	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;
                        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=_su+'/index.php';
		}
		else
			return false;
	}
	else
	{
		if(valFile != '')
			location.href=valFile;
		else
			location.href=_su+'/index.php';
	}
}
function newConfirmCancel(valMsg,valFile)
{
	if(valMsg != '')
	{
		if(confirm(valMsg))
		{
			if(valFile)
				location.href=valFile;
			else
				location.href=_su+'/index.php';
		}
		else
			return false;
	}
	else
	{
		if(valFile != '')
			location.href=valFile;
		else
			location.href=_su+'/index.php';
	}
}

//Function to give alert to those users who do not use standard browsers
function diffBrowser()
{
	alert(msgDifferentBrowser);
}

//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(_su+'/popUpLogin.php?M=OnlyForRegisteredUser',350,320,'nf_login');
		else
			openImg(_su+'/popUpLogin.php?M=OnlyForRegisteredUser',350,320,'nf_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() {}

/* newly  added function starts here */
function changeItemCategory(itemTypeList,itemCatList,currVal)
{
	var catOpt;

	//Remove all categories from the list except the first entry
	if(itemCatList.options.length > 0)
	{
		itemCatList.options.length=1;
		itemCatList.options[0].selected=true;
	}

	//Getting selected item type
	id_item_type=itemTypeList.value;file:///home/akhtar/webroot205/nettikirpputori.com/script.nettikirpputori.com/www/extra/template/nf_common.js

	//Fill the list box with categories of the selected item type
	if(icati[id_item_type])
	{
		var i=0;
		while(icati[id_item_type][i])
		{
			//Create new option and add that option to the category list box
			if(navigator.userAgent.match(/IE/))
			{
				catOpt = document.createElement('Option');

				catOpt.value=icati[id_item_type][i];
				catOpt.innerText=icatn[id_item_type][i];

				if(currVal == icati[id_item_type][i])
					  catOpt.selected = true;

				itemCatList.appendChild(catOpt);
			}
			else
			{
				catOpt= new Option(icatn[id_item_type][i],icati[id_item_type][i]);

				if(currVal == icati[id_item_type][i])
					catOpt.selected = true;

				itemCatList.options.add(catOpt);
			}

			i++;
		}
	}
}

function changeItemSection(itemTypeList,itemCatList,itemSecList,currVal)
{
	var opt;

	//Remove all categories from the list except the first entry
	if(itemSecList.options.length > 0)
	{
		itemSecList.options.length=1;
		itemSecList.options[0].selected=true;
	}

	//Getting selected item type
	id_item_type=itemTypeList.value

	//Getting selected item category
	id_item_cat=itemCatList.value;

	//Fill the list box with categories of the selected item type
	if(id_item_type > 0)
	{
		if(iseci[id_item_type][id_item_cat])
		{
            if(document.getElementById('star'))
                document.getElementById('star').style.display='inline';

			var i=0;
			while(iseci[id_item_type][id_item_cat][i])
			{
				//Create new option and add that option to the category list box
				if(navigator.userAgent.match(/IE/))
				{
					opt = document.createElement('Option');

					opt.value=iseci[id_item_type][id_item_cat][i];
					opt.innerText=isecn[id_item_type][id_item_cat][i];

					if(currVal == iseci[id_item_type][id_item_cat][i])
						opt.selected = true;

					itemSecList.appendChild(opt);
				}
				else
				{
					opt= new Option(isecn[id_item_type][id_item_cat][i],iseci[id_item_type][id_item_cat][i]);

					if(currVal == iseci[id_item_type][id_item_cat][i])
						opt.selected = true;

					itemSecList.options.add(opt);
				}

				i++;
			}
		}
        else
        {
            if(document.getElementById('star'))
                document.getElementById('star').style.display='none';
        }
	}
}
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()
{
//	$('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 modalForm(frmObj,st)
{
	var flag='N';
	var page_from = frmObj.page_from.value;
	var login_page;

	if(page_from.search('simple_dealer') == -1)
		login_page = _su+'/login.php?ajxLogin=1'
	else
		login_page = _su+'/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")
                {
                    if(frmObj.postad.value == 1)
                    {
                        if(st == 'EL' || st == 'KP')
                            window.location.href = _su + '/addEditItemImage.php';
                        else
                            window.location.href = _su + '/postAd.php';
                    }
                    else if(frmObj.redirectPage && frmObj.redirectPage.value != '')
                        window.location.href=frmObj.redirectPage.value;
                    else
                        window.location.reload();
                }
                else if(response.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";
}

function sd_loginmodal()
{
	document.getElementById("que_modal").blur();
	lightbox.prototype.content = _su+"/modalLogin.php?mainOnly=1&sd=1";
	lightbox.prototype.activate();
	idiv('lightbox').style.top = "60%";
	idiv('lightbox').style.width = "295px";
}

function ajaxcall(formObj,containerName)
{
	formObj.ajxifrm.value = 'A';
	var pars = Form.serialize($(formObj.name));
    AjaxUpdater(containerName, _su+'/viewItem.php?' + pars);
	return false;
}

function sd_ajaxQue(formObj,var_O)
{
	if(checkQue(formObj,var_O) != false )
	{
        document.getElementById('loaderimg').style.display='inline';
		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 answer = formObj.replyToQue.value;
        var xmlHttpReq=createXHR();

        xmlHttpReq.open('GET',_su+'/simple_dealer/sd_questionAnswer.php?ajxQueAns=1&ajx=1&' + pars,true);
        xmlHttpReq.setRequestHeader("Content-Type", "text/html;charset=UTF-8");
        xmlHttpReq.onreadystatechange=function() {
            if(xmlHttpReq.readyState == 4) {
                var str = xmlHttpReq.responseText;
                ary = str.split("$1#2*3#903");
                idiv('submitXQA').innerHTML = ary[0];
                var queToSeller=document.getElementById('askToSeller');

                var errorMsgId=1;
                if(document.getElementById('errorMsg') && document.getElementById('errorMsg').innerHTML)
                    errorMsgId=0;

                if(errorMsgId)
                {
                    if(answer == '1')
                        setTimeout("BlinkAnswer(ary[1]);",1000);
                    else
                        blinkingText_1('blink_que','blinking_qa','q_odd',3,0);
                }
                else
                {
                    queToSeller.style.display='block';
                    idiv('sendQueLink').className='arrow_hide_small';
                }

                idiv('loaderimg').style.display='none';
            }
        }
        xmlHttpReq.send(null);
        return false;
	}
	else
		return false;
}
function sd_ajaxLoadImage(id)
{
	var qa_id = id;
	if(document.getElementById('nf_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&ajx=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;
}
//		For Question-Answer part
function ss_ajaxQue(formObj,var_O)
{
	if(checkQue(formObj,var_O) != false )
	{
		document.getElementById('loaderimg').style.display='inline';

		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_seller/ss_questionAnswer.php?ajxQueAns=1&ajx=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);
                idiv('loaderimg').style.display='none';            }
        }
        xmlHttpReq.send(null);
        return false;
	}
	else
		return false;
}
function ss_ajaxLoadImage(id)
{
	var qa_id = id;
	if(document.getElementById('nf_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_seller/ss_questionAnswer.php?ajxQueAns=1&ajx=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
    idiv('lightbox').style.left='40%';
    if(opt == 'D')
    {
        pageURL=_su+'/modalLogin.php?mainOnly=1&sd=1';
        idiv('lightbox').style.left = '65%';
    }
    else if(opt == 'N')
    {
        pageURL=_su+'/modalLogin.php?mainOnly=1&sd=0';
        idiv('lightbox').style.left = '40%';
    }
    else if(opt == 'P')
        pageURL=_su+'/modalLogin.php?mainOnly=1&postad=1';
	else if(opt == 'RP')
	{
	    pageURL=_su+'/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();

    lightbox.prototype.content = pageURL;
    lightbox.prototype.activate();
    idiv('lightbox').style.top='65%';
    idiv('lightbox').style.width='295px';
}
//		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;
}

/**	To blink question and answers submitted by user */
function BlinkAnswer(str)
{
	var replyId = '';
	ansAry = str.split("#");
	for(var i = 0;i < ansAry.length-1;i++)
	{
		replyId = 'reply' + ansAry[i];
		blinkingText_1(replyId,'blinking_qa','r_odd',3,0);
	}
}

/** 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_item='+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 toggleElementDisplay(targetID)
{
    if(document.getElementById(targetID).style.display == "none")
        document.getElementById(targetID).style.display="block";
    else
        document.getElementById(targetID).style.display="none";
}

function chkTxtVal(theForm,strQry,fromWhere)
{
	if(fromWhere == 'NF' || fromWhere == 'EL')
	{
		if(theForm.auctionAds.checked != true)
		{
			if(theForm.q.value == '' || theForm.q.value == strQry )
			{
				alert(msgSelCrit);
				theForm.q.focus();
				return false;
			}

			if(theForm.q.value.match(/^[0-9]{1,50}$/) && theForm.fws.value == 'A')
			{
				alert(msgIdSearch);
				theForm.fws.focus();
				return false;
			}

			if(theForm.fws.value == 'NF' || !theForm.q.value.match(/^[0-9]{1,50}$/))
				document.solr_search.target='';
			else
				document.solr_search.target='formResults';
		}
	}
    else
	{
		if(theForm.q.value == '' || theForm.q.value == strQry)
		{
			alert(msgSelCrit);
			theForm.q.focus();
			return false;
		}
	}
    return true;
}

// Change CSS when tab is selected
function menuSwap(onMenu)
{
	var setElementNm='';

	if(document.getElementsByName('searchTabMenu'))
	{
		setElementNm='searchTabMenu';
		setClassNm='menuButton';
	}

	//turn off all buttons
	var menu = document.getElementsByName(setElementNm);

	for (var i = 0; i < menu.length; i++)
	{
		classChange(menu[i].id, setClassNm);
	}

	//turn on current button/layer
	classChange(onMenu, 'onmenuButton');
}

// change class function
function classChange(mytarget, myclass)
{
	if (document.getElementById(mytarget))
		document.getElementById(mytarget).className=myclass;
}
/**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=NF';

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

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

    return str.toLowerCase();
}
/** This function is return whole url with append of selected search criteria*/
function cleanUrl(qs)
{
    var mk=qs.elements.id_item_type.options[qs.elements.id_item_type.selectedIndex];
    var md=qs.elements.id_item_category.options[qs.elements.id_item_category.selectedIndex];
    var atype=qs.elements.ad_type.options[qs.elements.ad_type.selectedIndex];
    var u=_su+'/markkinapaikka';
    var l =qs.elements.length;

    if(mk.value)
        u=u+'/'+cleanRewriteUrl(s_itypn_fi[qs.elements.id_item_type.selectedIndex-1]);
    if(md.value)
        u=u+'/'+cleanRewriteUrl(s_icatn_fi[mk.value][qs.elements.id_item_category.selectedIndex-1]);
    if(atype.value)
    {
        var arrAdtype=new Array();
        arrAdtype['A']='huutokaupataan';
        arrAdtype['F']='myydaan';
        arrAdtype['P']='ostetaan';
        arrAdtype['E']='vaihdetaan';
        arrAdtype['G']='annetaan';
        arrAdtype['C']='vastaanotetaan';
        u=u+'/'+arrAdtype[atype.value];
    }

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

    mk.value=md.value=atype.value='';
    for(var i = 0; i < l; i++)
    {
        var e=qs.elements[i];

        if(e.name!='search')
        {
            if(e.value && e.type == 'hidden')
                u=u+e.name+'='+e.value+'&';
            if((e.value && e.type == 'select-one') ||(e.type == 'checkbox' && e.checked))
                u=u+e.name+'='+e.value+'&';
            if(e.type == 'select-multiple')
            {
                while (e.selectedIndex != -1)
                {
                    if (e.selectedIndex != 0)
                        u=u+e.name+'='+e.options[e.selectedIndex].value+'&';
                    e.options[e.selectedIndex].selected = false;
                }
            }
        }
    }
    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;
}

function getDomTown(domVal,curval,page,arena_area,sCode)
{
	var townStr='';
	var site='';
	var townUrl='http://'+location.hostname+'/ajaxGetDomicileTown.php?ajxifrm=A&frm='+page+'&';

   	if(curval) townStr='&sel_id_town='+curval;
	if(arena_area) townStr +='&arena_area='+arena_area;
	if(sCode) site='&site='+sCode;
	
	if(page == 'ADV')
		AjaxUpdater('adv_id_town',townUrl+'id_domicile='+domVal+townStr+site,"callAjax(document.adv);");
	else if(page == 'SIMP')
		AjaxUpdater('srch_id_town',townUrl+'id_domicile='+domVal+townStr);
	else if(page == 'POST')
		AjaxUpdater('post_id_town',townUrl+'id_domicile='+domVal+townStr+site);
	else if(page == 'listService')
		AjaxUpdater('service_id_town',townUrl+'id_domicile='+domVal+townStr);
}