var separator= "-";
var minYear = 1890;
var oReq = getXMLHttpRequest();
var xmlDoc = loadXML('../CountryAgeMapping.xml');


/*****************************************************************************************************
* Description : Loading the CountryAge mapping XML 
*
* Parameters : Path for the xml
*
* Return Value : void
********************************************************************************************************/
function loadXML(xmlFile) 
{

    if (oReq != null) {
        oReq.open("GET", xmlFile, true);
        oReq.onreadystatechange = handler;
        oReq.send();
        return oReq.responseXML;
    }
    else {
        window.alert("AJAX (XMLHTTP) not supported.");
        return null;
    }
	
	
}

function handler() {
    if (oReq.readyState == 4 /* complete */) {
        if (oReq.status == 200) {
            return oReq.responseText;
        }
    }
}



function getXMLHttpRequest() {
    if (window.XMLHttpRequest) {
        return new window.XMLHttpRequest;
    }
    else {
        try {
            return new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        catch (ex) {
            return null;
        }
    }
}

/*****************************************************************************************************
* Description : reading the nodes (MinimumAgeLimit and Country) value from XML and putting in an array
*
* Parameters : String Date
*
* Return Value : void
********************************************************************************************************/
function parseXML(strAge){
	var nodesAge = xmlDoc.getElementsByTagName('MinimumAgeLimit');	
	var legalPassingAge = new Array();
	var i = nodesAge.length;	
	var node;	
	do {
		i = i - 1;
		node = nodesAge[i];
		value = getNodeValue(node);
		legalPassingAge[i] = value;
	} while (i);
	
	var nodesCountry = xmlDoc.getElementsByTagName('Country');	
	var country = new Array();
	i = nodesCountry.length;
	var nodesCountrylength=i;
	
	do {
		i = i - 1;
		node = nodesCountry[i];		
		value = getNodeValue(node);		
		country[i] = value;
	} while (i);

	valCountry(nodesCountrylength, strAge, legalPassingAge, country);
}

/*****************************************************************************************************
* Description : Getting the Permissible Age from XML corresponding to the country selected in JSP
*
* Parameters : Var nodesCountrylength, Var strAge, Var legalPassingAge, Array country
*
* Return Value : boolean
********************************************************************************************************/
function valCountry(nodesCountrylength, strAge, legalPassingAge, country){
	var ctry = document.validateLDAForm.Country;	
	var idclient  = ctry.selectedIndex;	
	var valueClient = ctry.options[idclient].text;	
	
	var passingage;
	if(idclient != 0){
		do{
		    
			nodesCountrylength = nodesCountrylength - 1;
			if(valueClient == country[nodesCountrylength])
			{
				passingage = legalPassingAge[nodesCountrylength];
				/*alert("passingage: " + passingage)*/			
				validateAgeSuccess(strAge, passingage);				 
			}				
		} while (nodesCountrylength);
		return true;
	}else{
		alert("Please Select Country");
		return false;
	}
}

function getNodeValue(node) {
	return node.firstChild ? node.firstChild.nodeValue : '';
}

/*****************************************************************************************************
* Description : Parsing the string date and checking if all characters are integer.
*
* Parameters : Var s
*
* Return Value : boolean
********************************************************************************************************/
function isInteger(s){
	var i;
	for (i = 0; i < s.length; i++){ 
		// Check that current character is a number or not.
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) return false;
	}
	// All characters are numbers.
	return true;
}

/*****************************************************************************************************
* Description : Removing "-" from MM-DD-YYYY
*
* Parameters : Var date, Var seperator 
*
* Return Value : Var (MMDDYYYY)
********************************************************************************************************/
function stripCharsInBag(dateStr, separator){
	var i;
	var returnString = "";
//	Search through string's characters one by one.
//	If character is not in bag, append to returnString.
	for (i = 0; i < dateStr.length; i++){ 
		var c = dateStr.charAt(i);
		if (separator.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}

/*****************************************************************************************************
* Description : Check if the year is leap year or not.
*
* Parameters : Var year
*
* Return Value : Var
********************************************************************************************************/
function daysInFebruary (year){
	//February has 29 days in any year evenly divisible by four,
	//EXCEPT for centurial years which are not also divisible by 400.
	return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

/*****************************************************************************************************
* Description : Returns no of days in a particular month
*
* Parameters : Var n (Here n =12)
*
* Return Value : var
********************************************************************************************************/
function DaysArray(n) {	
	for (var i = 1; i <= n; i++) {
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30;}
		if (i==2) {this[i] = 29;}
	} 
	return this;
}

/*****************************************************************************************************
* Description : Check if the Date given by the consumer is the valid date
*
* Parameters : Var dateStr
*
* Return Value : boolean
********************************************************************************************************/
function isDate(dateStr){
	var daysInMonth = DaysArray(12);
	var pos1=dateStr.indexOf(separator);
	var pos2=dateStr.indexOf(separator,pos1+1);
	var strMonth=dateStr.substring(0,pos1);
	var strDay=dateStr.substring(pos1+1,pos2);
	var strYear=dateStr.substring(pos2+1);
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	}
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : MM-DD-YYYY");
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month");
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day");
		return false;
	}
	if (strYear.length > 4 || year==0 || year<minYear ){
		alert("Please enter a valid year greater than "+minYear);
		return false;
	}
	if (dateStr.indexOf(separator,pos2+1)!=-1 || isInteger(stripCharsInBag(dateStr, separator))==false){
		alert("Please enter a valid date");
		return false;
	}
	strAge = CalculateAge(month,day,year);
	if(strAge!=null)
		parseXML(strAge);
	return true;
}

/*****************************************************************************************************
* Description : Calculate age of consumer.
*
* Parameters : Var month, Var day, Var year
*
* Return Value : boolean
********************************************************************************************************/
function CalculateAge(month,day,year)
{
	today=new Date();	
	var age;
	age = today.getFullYear()- year;
	/*alert("Consumer's Age :" + age);*/
	return age;	
}


/*****************************************************************************************************
* Description : Validate if consumer's age is permissible.
*
* Parameters : Var Consumer's age, Var passingage
*
* Return Value : boolean
********************************************************************************************************/

function validateAgeSuccess(age, passingage)
{	
    /*alert("validateAgeSuccess");*/
	today=new Date();
	var todayMonth = today.getMonth()+1;	
	if (passingage != 0 && (age>passingage)||(age == passingage && todayMonth > month) ||(age == passingage && todayMonth == month && today.getDate() > day)){	
		/*alert("Permissible age is " + passingage);
		alert("Age is permissible");*/
		document.cookie = "AgeValidationSucess";
		window.location="Default.aspx";	
		return true;		
	} else {
		validateAgeFailure(passingage);	
		return true;
	}
}

/***************************************************************************************************************
* Description : If consumer's age is not permissible then redirect to the website "http://www.centurycouncil.org/
*
* Parameters : Var passingage
*
* Return Value : void
*****************************************************************************************************************/
function validateAgeFailure(passingage){
	if(passingage == 0){
		ValidateAgeDry(passingage);		
	}
	else{
		alert("Permissible age is " + passingage);
		alert("Age is not permissible");
		window.location="http://www.centurycouncil.org/";	
	}
}

/*****************************************************************************************************
* Description : Checking If permissible Age is 0
*
* Parameters : Var passingage
*
* Return Value : boolean
********************************************************************************************************/
function ValidateAgeDry(passingage){
	alert("Permissible age is " + passingage);
	alert("Its a DRY Country");
	return true;
}

/*****************************************************************************************************
* Description : Getting date from JSP
*
* Parameters : home
*
* Return Value : boolean
********************************************************************************************************/
function ValidateDate(home){
	var date=document.home.txtDate;
	if (isDate(date.value)== false){
		date.focus();
		return false;
	}
	return true;
}
