/* $Id: common.js,v 1.18 2010/01/21 11:03:57 amar Exp $ */

/** Function which checks whether given email is valid or not */
function emailInvalid(s)
{
    if(s.match(/^\w+([\.\+]?[-]{0,2}\w+)*[\.]?[-]?@\w+([\.-]?\w+)*(\.\w{2,4})+$/i))
        return true;
    else
        return false;
}
/** Function which checks whether given url address is valid or not */
function urlInvalid(s)
{
    if(!(s.match(/^http:\/\//i)))
        return false;
    else
        return true;
}
/** Function to check phone,fax,mobile for finland country */
function check(s)
{
    if(!s.match(/^[0-9\s\+-]{5,25}$/) )
        return false;
    else
        return true;
}
/** Function to check whether given string is really empty or not */
function isblank(s)
{
    for(var i=0; i < s.length; i++)
    {
        var c=s.charAt(i);

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

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

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

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

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

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

        if(rightSSN == p)
            return true;
        else
            return false;
    }
    return false;
}
/**
Function to give the user a message to login to the site, when he tries to access the feature
which is only for registered memeber.
*/
function loginWarning(msgWar,curTxt)
{
    if(!isblank(curTxt))
       alert(msgWar);
}

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

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

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

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

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

/** Function to open the new window with given width and height */
function openNewWin(varUrl,w,h,varTitle)
{
    var myfeatures='directories=no,location=no,menubar=no,status=yes,titlebar=no,toolbar=no,resizable=no,scrollbars=no,width='+w+',height='+h+',left=0,top=0';

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

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

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

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

    bCount++;

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

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

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

/** Function to submit navigation*/
function submitNavVif(pno,adId)
{
    document.nav.page.value=pno;
    document.nav.action +=adId;
    document.nav.submit();
}
/** Sort displaying vehicle list page according to specified arguments. */
function sortForm(col,ord)
{
    document.sortl.sortCol.value=col;
    document.sortl.ord.value=ord;
    document.sortl.submit();
}
//Function to return nothing, this is used sometimes
//to display tool tip on plain text by making trick
function returnVoid() {}

/** Function to confirm the cancel event and redirect to given file or home page */
function confirmCancel(valMsg,valFile)
{
    if(valMsg != '')
    {
        if(confirm(valMsg))
        {
            if(valFile)
                location.href=valFile;
            else
                location.href='home.php';
        }
        else
            return false;
    }
    else
    {
        if(valFile != '')
            location.href=valFile;
        else
            location.href='home.php';
    }
}
/** Function to confirm for form reset. */
function confirmReset()
{
    if(confirm(msgConfirmReset))
        return true;

    return false;
}
/**To popup message while removing single records */
function confirmDel(ref)
{
    if(confirm(msgDelConfirm))
        window.location.replace(ref);
}
/*
Argument 'label' can be the entity name you want to delete,
for exa., user,dealer,ad etc. and 'nm' can be the user name,
dealer name or ad id etc.
*/
function newConfirmDel(ref,label,nm)
{
    if(confirm(msgNewDeleteConfirm+" "+label+", '" + nm + "'?"))
        window.location.replace(ref);
}

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

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

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

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

    if(tot_image > 0)
    {
        for(j=1; j<=tot_image; j++)
        {
            if(document.getElementById('zoom_'+j))
            {
                document.getElementById('zoom_'+j).innerHTML='';
                document.getElementById('zoom_image_icon').style.display='block';
            }
        }
        if(document.getElementById('zoom_'+lImg_idNo))
            document.getElementById('zoom_'+lImg_idNo).innerHTML='<img style="cursor:pointer;" class="img png" src="'+commonImageUrl+'/zoom_modal_icon.png" width="24" height="24" />';
    }
    if(img_width)
        document.getElementById('zoom_image_icon').style.width=img_width+'px';
}

/** Koneet check Enable/Disable Prices **/
function chkDisable(field_name,verticle)
{
  var values=document.getElementById(field_name).value;

  if(field_name == 'tax_free_price')
  {	 
	  if(document.getElementById('taxable_price'))
	  {	
		if(values.length > 0)
		{
		  document.getElementById('taxable_price').style.background='#A1A1A1';
		  document.getElementById('taxable_price').style.color='#FFFFFF';
		  document.getElementById('taxable_price').value='Lasketaan automaat.';
		}
	  }
  }
  else
  {	  
	if(values.length > 0)
	{
	  document.getElementById('tax_free_price').style.background='#A1A1A1';
	  document.getElementById('tax_free_price').style.color='#FFFFFF';
	  document.getElementById('tax_free_price').value='Lasketaan automaat.';
	}
  }

  if(document.getElementById('tax_free_price').value.length == 0 )
  {
	document.getElementById('taxable_price').value='';
	document.getElementById('taxable_price').style.background='#FFFFFF';
	document.getElementById('taxable_price').style.color='#000000';
  }  

  if(document.getElementById('taxable_price'))
  {	  
	if(document.getElementById('taxable_price').value.length == 0)
	{
		document.getElementById('tax_free_price').value='';
		document.getElementById('tax_free_price').style.background='#FFFFFF';
		document.getElementById('tax_free_price').style.color='#000000';
	}
  }
}

/** function which checks the value which is only number*/
function updateNumField(o,flag)
{
    if(flag == 1)
        var t=frmCheckUIntFloat(o.value);
    else
        var t=frmCheckUInt(o.value);

    if (t)
        frmD[o.name]=o.value;
    else
        o.value=(frmD[o.name]!=null?frmD[o.name]:'');

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

function frmCheckUInt(o)
{
    for (var i=0;i < o.length;i++)
    {
        var c=o.charAt(i);
        if (!c.match(/^[0-9]+$/))
            return false;
    }
    return true;
}

function frmCheckUIntFloat(o)
{
    for (var i=0;i < o.length;i++)
    {
        var c=o.charAt(i);
        if (!c.match(/^[0-9\.,]+$/))
            return false;
    }
    return true;
}

function ShowOrHide(items)
{
    if(items)
    {
        var itemsArray=items.split(',');
        if(itemsArray.length > 0)
        {
            for(i=0; i < itemsArray.length; i++)
            {
                if($(itemsArray[i]).style.display=='block' || $(itemsArray[i]).style.display=='')
                {
                    $(itemsArray[i]).style.display='none';
                }
                else if($(itemsArray[i]).style.display == 'none')
                {
                    $(itemsArray[i]).style.display='';
                }
            }
        }
    }
}
/** Function to show the share bubble modal in ad information page. */
function shareModal(opt,e,id_ad,page_title)
{
    /** For getting the height of the page */
    var yScroll;

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

    var windowHeight;

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

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

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

        pageURL='vifBubbleShare.php?page_title='+page_title+'&id_ad='+id_ad;
        $('lightbox').style.left='41%';

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

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

        $('lightbox').style.width='430px';
        lightbox.prototype.content=pageURL;
        lightbox.prototype.activate(setScroll,pageHeight);
    }
}
// Function to open new pop up window with variable width and height
function openImg(img_nm,w,h,nm)
{
    var myfeatures='directories=no,location=no,menubar=no,status=yes,titlebar=no,toolbar=no,resizable=yes,scrollbars=yes,width='+w+',height='+h+',left=0,top=0';

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

    var newImg=open(img_nm,nm,myfeatures);
    //newImg.focus();
}
function submitForm(item)
{
    if (typeof item.onsubmit == "function") {
        item.onsubmit();
    }

    item.submit();
}
/** Function to change the video status From admin. */
function changeVideoStatus(idAd,videoStatus,sCode)
{
    if(!sCode)
        return;
    else if(sCode == 'NA')
        video_url='/cars';
    else if(sCode == 'NH')
        video_url='/house';
    else if(sCode == 'NK')
        video_url='/machines';
    else if(sCode == 'NP')
        video_url='/parts';
    else if(sCode == 'NF')
        video_url='/tori';

    if(confirm(msgChangeStatus))
    {
        new Ajax.Updater('vStatus'+idAd,
                            video_url + '/extra/admin/changeVideoStatus.php',
                            {
                                method: 'get',
                                parameters:
                                {
                                    id_ad: idAd,
                                    site_code: sCode,
                                    video_status: videoStatus,
                                    ajxifrm: 'A'
                                }
                            }
                        );
    }
    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)
{
    var pars='ajxifrm=A';

    new Ajax.Updater(id_element,videoUrl,{asynchronous:true,parameters:pars,evalScripts:true});
}


// 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 put default value in text box input field, given id and default value */
function setDefaultText(fieldId,fieldVal,defVal)
{
    if(fieldVal == defVal)
        document.getElementById(fieldId).value='';
    else
        document.getElementById(fieldId).value=fieldVal;
}
/** function which checks the value which is Alphabets */
function checkAlphabet(o,advSearchFlg)
{
    for(var i=0;i < o.value.length;i++)
    {
        var c=o.value.charAt(i);
        if(advSearchFlg)
        {
            if (c.match(/^[0-9a-zA-ZåÅäÄöÖÁÀÉÈÒÓÙÚáàèéòóùúÝìíýÌÍ\s+,]$/))
                t=1;
            else
                t=0;
        }
        else
        {
            if (c.match(/^[a-zA-ZåÅäÄöÖÁÀÉÈÒÓÙÚáàèéòóùúÝìíýÌÍ\s]$/))
                t=1;
            else
                t=0;
        }
    }

    if (t)
        frmD[o.name]=o.value;
    else
        o.value=(frmD[o.name]!=null?frmD[o.name]:'');

    o.focus();
}


/*
    Function disable the price text box and fill with 'Ei hinnoiteltu'
    when no price check box is checked and make that price field to optional
*/
function noPriceCheck(firstPrice,secondPrice,noprice)
{
    if(noprice.checked)
    {
        $('#'+firstPrice).attr('maxlength',15);
        $('#'+secondPrice).attr('maxlength',15);

        $('#'+firstPrice).val('Ei hinnoiteltu');
        $('#'+secondPrice).val('Ei hinnoiteltu');
        $('#'+firstPrice).attr('disabled',true);
        $('#'+secondPrice).attr('disabled',true);
	  
		if(document.getElementById('tax_free_price'))
		{
		  document.getElementById('tax_free_price').style.background='#A1A1A1';
		  document.getElementById('tax_free_price').style.color='#FFFFFF';
		}
		if(document.getElementById('taxable_price'))
		{
		  document.getElementById('taxable_price').style.background='#A1A1A1';
		  document.getElementById('taxable_price').style.color='#FFFFFF';
		}
    }
    else
    {
        $('#'+firstPrice).attr('maxlength',10);
        $('#'+secondPrice).attr('maxlength',10);

        $('#'+firstPrice).val('');
        $('#'+secondPrice).val('');

        $('#'+firstPrice).attr('disabled',false);
        $('#'+secondPrice).attr('disabled',false);

		if(document.getElementById('tax_free_price'))
		{
		  document.getElementById('tax_free_price').style.background='#FFFFFF';
		  document.getElementById('tax_free_price').style.color='#000000';
		}
		if(document.getElementById('taxable_price'))
		{
		  document.getElementById('taxable_price').style.background='#FFFFFF';
		  document.getElementById('taxable_price').style.color='#000000';
		}
    }

    $('#'+firstPrice).blur();
    $('#'+secondPrice).blur();
}

function noRegCheck(regNo,show_reg,no_reg)
{
    if(no_reg.checked)
    {
        $('#'+regNo).val('Ei rekisteröity');
        $('#'+regNo).attr('disabled',true);
        $('#'+show_reg).attr('checked',false);
        $('#'+show_reg).attr('disabled',true);
    }
    else
    {
        $('#'+regNo).val('');
        $('#'+regNo).attr('disabled',false);
        $('#'+show_reg).attr('disabled',false);
    }

    $('#'+regNo).blur();
}

function setNoPriceCheck(no_price_chk,price_text,h_price,h_no_price_chk)
{
    /** If any error msg comes than need to reset noprice checkbox  */
    if(document.getElementById(h_no_price_chk))
    {
        $('#'+no_price_chk).attr('checked',true);
        $('#'+price_text).attr('maxlength',15);
        $('#'+price_text).val('Ei hinnoiteltu');
        $('#'+price_text).attr('disabled',true);
    }
    /** If price field is not blank during error msg than uncheck noprice check box */
    else if(document.getElementById(h_price) && document.getElementById(h_price)!='')
    {
        $('#'+no_price_chk).attr('checked',false);
        $('#'+price_text).attr('disabled',false);
    }
}

function setNoRegCheck(no_reg_chk,show_reg,reg_text,h_show_reg2,h_regno)
{
    /** If any error msg comes than need to reset noreg checkbox  */
    if(document.getElementById(h_show_reg2))
    {
        $('#'+no_reg_chk).attr('checked',true);
        $('#'+show_reg).attr('checked',false);
        $('#'+show_reg).attr('disabled',true);
        $('#'+reg_text).val('Ei rekisteröity');
        $('#'+reg_text).attr('disabled',true);
    }
    /** If regno is not blank during error msg than  uncheck that no_reg check box */
    else if(document.getElementById(h_regno) && document.getElementById(h_regno)!='')
    {
        $('#'+no_reg_chk).attr('checked',false);
        $('#'+show_reg).attr('disabled',false);
        $('#'+reg_text).attr('disabled',false);

        if(document.getElementById('h_show_reg'))
            $('#'+show_reg).attr('checked',true);
        else
            $('#'+show_reg).attr('checked',false);
    }
}

function chkTown()
{
	var geo_location = $("#geolocation").attr('value');

	if(geo_location == 'Syötä paikkakunta')
		$("#geolocation").attr('value','')
}