﻿/*
 * qValidation 
 * Version: 1.0
 *
 * Copyright (c) 2009 Quy Nguyen
 * Dual licensed under the MIT and GPL licenses.
 * http://docs.jquery.com/License
 *
 * Date: 2009-07-21 11:05:21 (Tuesday, 21 July 2009)
 
 * Revision: n/a
 */

function DisplayTipMsg(obj,objName)
{
//alert("tip: " + objName + " value: " + obj.value);
    if (_controlName==""){_controlName="123xyz";}  //create a dummy value for _controlName if it's not defined
    if (obj.id == objName && (obj.value=='' || obj.value.toLowerCase()=='yyyy'  || obj.value.toLowerCase()=='aaaa')) 
    {
        $('#empty_' + objName).hide();
        $('#invalid_' + this.id).hide();
        $("#label_" + replace(objName,_controlName,'')).removeClass("fRed");
        $('#popuup_' + objName).css({left:leftVal,top:topVal}).fadeIn(fadingInSpeed).show();
        return false;
    }
    else
    {
        return true;
    }
}

function DisplayErrorMsg(obj,objName)
{  
//alert(obj.id + " " + objName);
    if (_controlName==""){_controlName="123xyz";}  //create a dummy value for _controlName if it's not defined
    if(obj.id == objName) 
    {
        //create a dynamic div to hold the OK image for the OK input field
        CreateDIV("img_OK_" + objName,"popup_msg");
        if (obj.value=='')
        {
            //alert("objname: " + objName + " controlName" + _controlName);
            
            $("#label_" + replace(objName,_controlName,'')).addClass("fRed");
            $('#popuup_' + objName).css({left:leftVal,top:topVal}).hide();
            $('#img_OK_' + objName).html("");
            //$('#empty_' + objName).css({left:leftVal,top:topVal}).fadeIn(fadingInSpeed).show().fadeOut(fadingOutSpeed);
            $('#empty_' + objName).css({left:leftVal,top:topVal}).fadeIn(fadingInSpeed).show();
        }
        else
        {            
            if (CheckWildChar(obj.value))
            {
                $("#label_" + replace(objName,_controlName,'')).addClass("fRed");
                $('#img_OK_' + objName).html("");
                $('#popuup_' + objName).css({left:leftVal,top:topVal}).hide();
                //$('#invalid_checkwildchar').css({left:leftVal,top:topVal}).fadeIn(fadingInSpeed).show().fadeOut(fadingOutSpeed);
                $('#invalid_checkwildchar').css({left:leftVal,top:topVal}).fadeIn(fadingInSpeed).show();
            }
/*         
            else if (obj.id.toLowerCase().indexOf("postal")>0)
            {            
                ValidatePostalCode(obj);
            }
*/
            else
            {
                $('#empty_' + objName).hide();
                $("#label_" + replace(objName,_controlName,'')).removeClass("fRed");
                $('#popuup_' + objName).css({left:leftVal,top:topVal}).hide();
                $('#invalid_checkwildchar').hide();
                //$('#img_OK_' + objName).css({left:leftVal,top:topVal}).html('<img src="images/accept.gif" border="0" style="float:right;" />');
                //alert ("here");
                //leftVal=leftVal+150;
                $('#img_OK_' + objName).css({left:leftVal,top:topVal}).html('<img src="images/accept.gif" border="0" style="float:left;" />');
            }
        }
    }
}

function CheckWildChar(strCheck)
{
    //var strMatch = /[(\*\(\)\[\]\+\.\,\/\?\:\;\"\`\~\\#\$\%\^\&\<\>)+]/;
    var strMatch = /[(\*\(\)\[\]\+\.\,\/\?\:\;\`\~\\#\$\%\^\&\<\>)+]/;
    if (!strCheck.match(strMatch)) 
    {
        return false;
    } 
    else 
    {
        return true;
    }
}

function CreateDIV(divID,divStyle)
{
//alert(divID + " - left: " + leftVal + " - top: " + topVal);
    dv = document.createElement('div'); // create dynamically div tag
    dv.setAttribute('id',divID);       //give id to it
    dv.className=divStyle;     
    //set the html content inside the div tag
    //dv.innerHTML='Your_HTML_content';

    // attach event onmouseclick to the created div tag 
    //dv.attachEvent("onmouseclick",function(){element_event_onmouseover();}); 

    //finally add the div id to ur form 
    document.forms[0].appendChild(dv);
}


function CreateDIVContent(divID,divStyle,divContent)
{
    dv = document.createElement('div'); // create dynamically div tag
    dv.setAttribute('id',divID);       //give id to it
    dv.className=divStyle;     
    //set the html content inside the div tag
    dv.innerHTML=divContent;
    
//    alert(divContent);
    // attach event onmouseclick to the created div tag 
    //dv.attachEvent("onmouseclick",function(){element_event_onmouseover();}); 

    //finally add the div id to ur form 
    //document.forms[0].appendChild(dv);
    //$("body").append(dv);
    $("#ErrorMsg_Client").append(dv);
}


function ValidateEmail(strEmail)
{
    //var strEmail=obj.value; 
    var strMatch  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (!strEmail.match(strMatch)) 
    {
        return false;
    } 
    else 
    {
        return true;
    }
}
/*
function ValidatePostalCode_OLD(obj,objName)
{
    var strPostal=obj.value;
    strPostal=replace(strPostal," ","",1,0); 
	strPostal=replace(strPostal,"-","",1,0); 
    if (!IsPostalCode(strPostal))
    {
        $('#img_OK_' + obj.id).html("");
        $('#popuup_' + obj.id).css({left:leftVal,top:topVal}).hide();
        $('#invalid_' + obj.id).css({left:leftVal,top:topVal}).fadeIn(fadingInSpeed).show().fadeOut(fadingOutSpeed);
    }
    else
    {
        $('#empty_' + obj.id).hide();
        $('#popuup_' + obj.id).css({left:leftVal,top:topVal}).hide();
        $('#checkwildchar').hide();
        $('#img_OK_' + obj.id).css({left:leftVal,top:topVal}).html('<img src="images/accept.gif" border="0" style="float:left;" />');
    }
}
*/
function ValidatePostalCode(obj,objName)
{
    var strPostal=obj.value;
    strPostal=replace(strPostal," ","",1,0); 
	strPostal=replace(strPostal,"-","",1,0); 
    if (!IsPostalCode(strPostal))
    {
        return false;
    }
    else
    {
        return true
    }
}

function ValidatePhone(obj)
{

    var strPhone=obj.value; 
    var checkLength=(obj.id.toLowerCase().indexOf("areacode")>0) ? 3: 7;
    if (obj.id.toLowerCase().indexOf("phone"))
    {
        CreateDIV("img_OK_" + "txtPhone","popup_msg")
    }
    
    if(!isInt(strPhone) || strPhone.length != checkLength)
    {
        return false;
    }
    else
    {
        return true;
    }
}

function ValidateDoB(obj)
{
    var resultVal=true;
    var strVal=obj.value; ;
    if (obj.id.toLowerCase().indexOf("year"))
    {
        CreateDIV("img_OK_" + "txtYear","popup_msg")
    }
    
    if (obj.value=="" || !isInt(obj.value) || obj.value.toLowerCase()=="yyyy" || obj.value.toLowerCase()=="aaaa")
    {
        resultVal=false;
    }
    return resultVal;
}

/*
Use this when you want to validate dob value in only one input textbox
function ValidateDoB(strCheck)
{
    var strMatch = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
    if (!strCheck.match(strMatch)) 
    {
        return false;
    } 
    else 
    {
        return true;
    }
}
*/



function FindPos(obj)
{
    this.posX= obj.offsetLeft;
    this.posY=obj.offsetTop;
    while(obj.offsetParent)
    {
        this.posX += obj.offsetParent.offsetLeft;
        this.posY += obj.offsetParent.offsetTop;
        if(obj==document.getElementsByTagName('body')[0]){break}
        else{obj=obj.offsetParent;}
    }
}

//---------------------------------------------------------
function replace(target,oldTerm,newTerm,caseSens,wordOnly) {
	
		var work = target;
		var ind = 0;
		var next = 0;
	
		if (!caseSens) {
		oldTerm = oldTerm.toLowerCase();
		work = target.toLowerCase();
		}
	
		while ((ind = work.indexOf(oldTerm,next)) >= 0) {
		if (wordOnly) {
			var before = ind - 1;
			var after = ind + oldTerm.length;
			if (!(space(work.charAt(before)) && space(work.charAt(after)))) {
			next = ind + oldTerm.length;
			continue;
			}
		}
		target = target.substring(0,ind) + newTerm + 
target.substring(ind+oldTerm.length,target.length);
		work = work.substring(0,ind) + newTerm + 
work.substring(ind+oldTerm.length,work.length);
		next = ind + newTerm.length;
		if (next >= work.length) { break; }
		}
		return target;  
}
    
//--------------------------------------------------
function IsPostalCode(PostOne) 
{     
//if(!FindBadCharacters(PostOne)  &&
if(!CheckWildChar(PostOne) &&	                                                                                                                        
	isNaN(PostOne.charAt(0))     && 
	!isNaN(PostOne.charAt(1))    &&
	isNaN(PostOne.charAt(2))     &&              
	!isNaN(PostOne.charAt(3))    &&
	isNaN(PostOne.charAt(4))     &&
	!isNaN(PostOne.charAt(5))    &&
		
	PostOne.length == 6)        
	{return true;}
	else
	{return false;}      
} 


//---------------------------------------------------------
function isInt(strVal){
		if(strVal == ""){return false;}
		//if(FindBadCharacters(strVal)){return false;}				
		if(CheckWildChar(strVal)){return false;}
		for(var i = 0; i <= strVal.length - 1; i++)
			{
				if(isNaN(strVal.charAt(i)))
					{return  false;}   	
			}
		return true;
} 



//---------------------------------------------------------
function DatePicker()
{

				// initialise the "Select date" link
				$('#date-pick')
					.datePicker(
						// associate the link with a date picker
						{
							createButton:false,
							startDate:'01/01/1930',
							endDate:'31/12/2009'
							
						}
					).bind(
						// when the link is clicked display the date picker
						'click',
						function()
						{
							updateSelects($(this).dpGetSelected()[0]);
							$(this).dpDisplay();
							return false;
						}
					).bind(
						// when a date is selected update the SELECTs
						'dateSelected',
						function(e, selectedDate, $td, state)
						{
							updateSelects(selectedDate);
						}
					).bind(
						'dpClosed',
						function(e, selected)
						{
							updateSelects(selected[0]);
						}
					);
					
				var updateSelects = function (selectedDate)
				{
					var selectedDate = new Date(selectedDate);
					$('#' + _controlName + 'ddDay option[value=' + selectedDate.getDate() + ']').attr('selected', 'selected');
					$('#' + _controlName + 'ddMonth option[value=' + (selectedDate.getMonth()+1) + ']').attr('selected', 'selected');
					$('#' + _controlName + 'txtYear').val(selectedDate.getFullYear());
					//$('#y option[value=' + (selectedDate.getFullYear()) + ']').attr('selected', 'selected');
					//document.getElementById('y2').value=selectedDate.getFullYear();
//					alert(selectedDate.getFullYear());
				}
				// listen for when the selects are changed and update the picker
				$('#Control_default_txtYear, #Control_default_ddMonth, #Control_default_ddDay')
					.bind(
						'change',
						function()
						{
							var d = new Date(
										/*
										$('#y').val(),
										$('#m').val()-1,
										$('#d').val()
										*/
										$('#' + _controlName + 'txtYear').val(),
										$('#' + _controlName + 'ddMonth').val()-1,
										$('#' + _controlName + 'ddDay').val()
										
									);
							$('#date-pick').dpSetSelected(d.asString());
						}
					);
				
				// default the position of the selects to today
				var today = new Date();
				//updateSelects(today.getTime());
				updateSelects(today.getTime());
				
				// and update the datePicker to reflect it...
				//$('#d').trigger('change');
				$('#' + _controlName + 'ddDay').trigger('change');
}


//---------------------------------------------------------
function LoadXMLDiv()
{ 
    $.ajax({
         type: "GET",
         url: qTrackURL + "xmlfiles/treasurehunt_" + _languageID + ".xml", //"./xmlfiles/" + _pageName + "_" + _languageID + ".xml",
         dataType: "xml",
         cache:false,
         async:false,
         success: function(xml) 
         {
         
           //retrieve all the children nodes's data in the'find' node
             $(xml).find("msg_popup").each(function(){
                $(this).find('item').each(function(){
                    //alert($(this).attr('label') + "..." + $(this).text());
                    var divPopUp_Content="<img class='msgbox_corner' src='/images/msgbox_corner.gif'  />" + 
                                   "<div id='tip_" + $(this).attr("label") + "' class='tip_msg'>" + $(this).text() + "</div>";
                    CreateDIVContent("popuup_" + _controlName + $(this).attr("label"),"popup_msg",divPopUp_Content);
                    
                });
             }); //close each(
             
             $(xml).find("msg_empty").each(function(){
                $(this).find('item').each(function(){
                    var divEmpty_Content="<img class='msgbox_corner' src='/images/msgbox_corner.gif'  />" + 
                                   "<div id='empty_" + $(this).attr("label") + "' class='error_msg'>" + $(this).text() + "</div>";     
                    CreateDIVContent("empty_" + _controlName + $(this).attr("label"),"popup_msg",divEmpty_Content);
                });
             }); //close each(
             
             $(xml).find("msg_invalid").each(function(){
                $(this).find('item').each(function(){
                    var divInvalid_Content="<img class='msgbox_corner' src='/images/msgbox_corner.gif'  />" + 
                                   "<div id='invalid_" + $(this).attr("label") + "' class='error_msg'>" + $(this).text() + "</div>";      
                    var invalidID= ($(this).attr("label")=="checkwildchar") ? "invalid_checkwildchar" : "invalid_" + _controlName + $(this).attr("label");
                    CreateDIVContent(invalidID,"popup_msg",divInvalid_Content);           
                });
             }); //close each(
           
//             OnSubmitCheck(xml);
         }
    });
}