/*** CHECK DATE FUNCTIONS ***/
// Declaring valid date character, minimum year and maximum year
d = new Date();
cYear = d.getUTCFullYear();
var minYear=cYear-100;
var maxYear=cYear+1;

function daysInFebruary (strYear){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    strYear = parseFloat(strYear);
    return (((strYear % 4 == 0) && ( (!(strYear % 100 == 0)) || (strYear % 400 == 0))) ? 29 : 28 );
}

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
}

function validate_year (strYear)
{
	if (strYear.length != 4 || parseFloat(strYear)==0 || parseFloat(strYear)<parseFloat(minYear) || parseFloat(strYear)>parseFloat(maxYear))
		return false;
 	else
		return true;
}

function validate_month(strMonth)
{
	if (strMonth.length<1 || parseFloat(strMonth)<1 || parseFloat(strMonth)>12)
		return false;
	else
		return true;
}

function validate_day(strDay, strMonth, strYear)
{
	var daysInMonth = DaysArray(12)
	if (strDay.length<1 || parseFloat(strDay)<1 || parseFloat(strDay)>31 || (parseFloat(strMonth)==2 && parseFloat(strDay)>daysInFebruary(strYear)) || parseFloat(strDay) > daysInMonth[strMonth])
		return false;
	else
		return true;
}

function isDate(dtStr){
	var pos1=dtStr.indexOf("/")
	var pos2=dtStr.indexOf("/",pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	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 (strYear.charAt(0)=="0" && strYear.length>1) strYear=strYear.substring(1)
	}
	if (
		(pos1==-1 || pos2==-1) ||
		!validate_year(strYear) ||
		!validate_month(strMonth) ||
		!validate_day(strDay, strMonth, strYear))
		return false;
	else
		return true;
}

 /// GENERAL FUNCTINS /////

function Set_Cookie( name, value, expires, path, domain, secure )
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain )
{
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// this function gets the cookie, if it exists
function Get_Cookie( name )
{
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) &&
	( name != document.cookie.substring( 0, name.length ) ) )
	{
	return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function checkEmail(str) {
///// function for validating email address
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)

		if (str.indexOf(at)==-1){
		    return false
		} else if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		    return false
		} else 	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		} else  if (str.indexOf(at,(lat+1))!=-1){
		    return false
		} else 	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		   return false
		} else  if (str.indexOf(dot,(lat+2))==-1){
		    return false
		} else if (str.indexOf(" ")!=-1){
		     return false
		} else {
 		 	return true
 		}
}

function checkMultipleEmail(emails, split_char)
{
	emails_array = emails.split(split_char);
	checkStatus = true;
	for (e in emails_array)
	{
		if (trim(emails_array[e]) != "" && !checkEmail(trim(emails_array[e])))
			checkStatus =false;
	}
	return checkStatus;
}

function checkML(emailValue)
{
	if(!checkEmail(emailValue))
	{
		alert (_tpl_emailNotValid);
		document.joinML.focus();
		return false;
	} else {
		var url = "xmlJoinML.php?joinML_email="+emailValue+"&siteLang="+siteLang;
		var xml = LoadXML(url);
		if(xml != null)
		{
			var message = xml.getElementsByTagName('rsp')[0].firstChild.data;
			alert(message);
			var response = xml.getElementsByTagName('rsp_stat')[0].firstChild.data;
			if (response)
				document.joinML.reset();
			else
				document.joinML.focus();
		}
		return false;
	}
}

function getHTTPObject()
{
	try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
	try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
	try { return new XMLHttpRequest(); } catch(e) {}
	alert("XMLHttpRequest not supported");
	return null;
 }

function LoadHTML(url)
{

	var xmlHttp = getHTTPObject();
	xmlHttp.open("GET",url, false);
	xmlHttp.onreadystatechange = function()
	{
		   if (xmlHttp.readyState != 4)  { return; }
		   var serverResponse = xmlHttp.responseText;

	}
	xmlHttp.send(null);
	return xmlHttp.responseText;
}
function LoadXML(url)
{
	var xmlHttp = getHTTPObject();
	xmlHttp.open("GET",url, false);
	xmlHttp.onreadystatechange = function()
	{
		   if (xmlHttp.readyState != 4)  { return; }
		   var serverResponse = xmlHttp.responseText;
	};
	xmlHttp.send(null);
	return xmlHttp.responseXML.documentElement;
}

// bulid string with the form values, fobj the form object, valFunc is validate function
function getFormValues(fobj)
{
   var str = "";
   var valueArr = null;
   var val = "";
   var cmd = "";

   for(var i = 0;i < fobj.elements.length;i++)
   {
       switch(fobj.elements[i].type)
       {
      	case "text":
           case "hidden":
           case "textarea":
           	str += fobj.elements[i].name + "=" + escape(fobj.elements[i].value) + "&";
           break;

           case "radio":
           case "checkbox":
               if(fobj.elements[i].checked)
               		str += fobj.elements[i].name + "=" + escape(fobj.elements[i].value) + "&";
           break;

           case "select-one":
                str += fobj.elements[i].name + "=" + fobj.elements[i].options[fobj.elements[i].selectedIndex].value + "&";
           break;
       }
   }

   str = str.substr(0,(str.length - 1));
   return str;
}

// validate is got the validate function, if false then skip the validation
function submitAjaxForm(f,url)
{
   var str = getFormValues(f);
   xmlReq = postAjaxForm(url ,str);

 }

 function postAjaxForm(url,str)
{
   var doc = null
   if (typeof window.ActiveXObject != 'undefined' )
   {
       doc = new ActiveXObject("Microsoft.XMLHTTP");

   }
   else
   {
       doc = new XMLHttpRequest();
       doc.onload = displayState;
   }

   doc.open( "POST", url, true );
   doc.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
   doc.send(str);
   return doc.responseXML.documentElement;
}

function showMessage(message, elementID)
{
	document.getElementById(elementID).innerText=message;
}

function clearMessage(elementID)
{
	document.getElementById(elementID).innerText="";
}


function IsNumeric(sText)
{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;


   for (i = 0; i < sText.length && IsNumber == true; i++)
      {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {
         IsNumber = false;
         }
      }
   return IsNumber;
 }

function trim(strText) {
/// TRIM STRING FUNCTION
    // this will get rid of leading spaces
    while (strText.substring(0,1) == ' ')
        strText = strText.substring(1, strText.length);
    // this will get rid of trailing spaces
    while (strText.substring(strText.length-1,strText.length) == ' ')
        strText = strText.substring(0, strText.length-1);
   return strText;
}

function escapeString(sString)
{
// DETECT WHAT TO PUT STRING IN FOR HTML FORM ( ' OR " ) DEPANDING ON STRING CONTENTS
	if (sString.indexOf("'") == -1)
		valSep = "'";
	else
		valSep = '"';
	return valSep+sString+valSep;
}

function replaceSubstring(inputString, fromString, toString) {
 // GOES THROUGH THE INPUTSTRING AND REPLACES EVERY OCCURRENCE OF FROMSTRING WITH TOSTRING
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
}

function popupWin(popUrl, width, height)
{
	if (!navigator.appName.indexOf("Microsoft")) width+=20;
	height+=5;
	topVar=((screen.height / 2)-(height/2));
	leftVar=((screen.width / 2)-(width/2));
	window.open(popUrl, "PopUp", "height="+height+", width="+width+", top="+topVar+", left="+leftVar+", scrollbars=yes, status=no, location=no, resize=yes, menubar=no, titlebar=no, toolbar=no");
}

function switchElementDisplay(elementID){
// SWITCH SELECTED ELEMENT DISPLAY: NONE/INLINE
	if (document.getElementById(elementID).style.display=="none")
		document.getElementById(elementID).style.display="inline";
	else
		document.getElementById(elementID).style.display="none";
}

function show_menu(menuID, page_code)
{
	// FUNCTION FOR CHANGING SUB MENUES ON SITE
	var url = "xml_getMenuData.php?menuID="+menuID;
//	window.clipboardData.setData('Text',url);
	var xml = LoadXML(url);
	if(xml != null && xml.getElementsByTagName('total_items')[0].firstChild.data > 0)
	{
//		clearTimeout(showMenuItem);
		var menu_div = document.getElementById("menu_mc");
		var total_items = xml.getElementsByTagName('total_items')[0].firstChild.data;
		menu_div.innerHTML = "";
		for (i=0;  i<total_items; i++)
		{
			item_text = xml.getElementsByTagName('item_'+i+'_name')[0].firstChild.data;
			item_link = xml.getElementsByTagName('item_'+i+'_menuLink')[0].firstChild.data;
			item_target = xml.getElementsByTagName('item_'+i+'_menuTarget')[0].firstChild.data;
			item_code = xml.getElementsByTagName('item_'+i+'_menuCode')[0].firstChild.data;
			cClass = (	page_code==item_code || 	page_code=="about" && item_code.indexOf(page_code) > 0) ? "selected":"";
			menu_div.innerHTML += "<a href='"+item_link+"' target='"+item_target+"' class='"+cClass+"'>"+item_text+"</a><p>|</p>";
//			showMenuItem = setTimeout("show_menu_item('"+item_text+"','"+item_link+"','"+item_target+"')",i*100);
		}
	}
}

function show_menu_item(item_text, item_link, item_target)
{
	var menu_div = document.getElementById("menu_mc");
	menu_div.innerHTML += "<a href='"+item_link+"' target='"+item_target+"'>"+item_text+"</a><p>|</p>";
}

function gotoSign()
{
	f=document.ast_find.myBirthdate;
	if (f.value == "")
	{
		alert (_alert_yourBirthdate);
		f.focus();
		return false;
	}
	else if (!isDate(f.value))
	{
		alert (_alert_dateNotValid);
		f.focus();
		return false;
	}
	else
	{
		url="xml_getSign.php?date="+f.value;
		var xml = LoadXML(url);
		if (xml.getElementsByTagName('sign')[0].firstChild.data)
		{
			location.href="horoscope.php?type=profile&id="+xml.getElementsByTagName('sign')[0].firstChild.data;
			return false;
		}
		else
		{
			alert(_alert_sign_notFound);
			return false;
		}
	}
}

function chineseZodiac()
{
	f = document.chineseMatch.myBirthyear;
	strYear = f.value;
	if(!validate_year(strYear))
	{
		alert(_alert_wrongYear );
		f.focus();
		return false;
	}
	else
	{
		location.href="Chinese Zodiac.php?myBirthyear="+f.value;
		return false;
	}
}

function checkMatch(formID)
{
	f=document.getElementById(formID);
	if (f.your_birthdate.value=="")
	{
		alert (_alert_yourBirthdate);
		f.your_birthdate.focus();
		return false;
	}
	if (f.partner_birthdate.value=="")
	{
		alert (_alert_partnerBirthdate);
		f.partner_birthdate.focus();
		return false;
	}

	if(isDate(f.your_birthdate.value) && isDate(f.partner_birthdate.value))
		return true;
	else
	{
		alert (_alert_dateNotValid);
		return false;
	}


}

function checkDestinyCalc(formID)
{
	f=document.getElementById(formID);
	if (f.your_birthdate.value=="")
	{
		alert (_alert_yourBirthdate);
		f.your_birthdate.focus();
		return false;
	}

	if(isDate(f.your_birthdate.value))
		return true;
	else
	{
		alert (_alert_dateNotValid);
		return false;
	}


}

function submitenter(myfield,e)
{
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13)
	   {
	   if(myfield.form.onsubmit())
	   	myfield.form.submit();
	   return false;
	   }
	else
	   return true;
}


function checkLogin()
{
	cForm=document.getElementById("login_form");

	if (cForm.userName.value == "" || cForm.password.value == "")
	{
		alert(alert_EnterUNPass_);
		if(cForm.userName.value == "")
			cForm.userName.focus();
		else if(cForm.password.value == "")
			cForm.password.focus();
	}
	else
	{
		// ajax check login
		var url = "xml_login.php?logMember=true&userName="+cForm.userName.value+"&password="+cForm.password.value;
//		window.clipboardData.setData('Text',url);
		var xml = LoadXML(url);
		if(xml != null)
		{
			if (xml.getElementsByTagName('login')[0].firstChild.data == "logged")
				location.reload();
			else
			{
				var message = xml.getElementsByTagName('rsp')[0].firstChild.data;
				alert (message);
				cForm.userName.focus();
			}
		}
	}
	return false;
}


function checkNewUserForm(formID)
{

	curForm=document.getElementById(formID);
	fArray=new Array("firstName","lastName","address","city","address","birthdate","email","userName","password","pwValidation");

	for (i=0;i<fArray.length; i++)
	{
		fieldName = fArray[i];
		if (curForm[fieldName].value=="")
		{
			cMessage = eval("_alert_"+fieldName);
			alert(cMessage);
			curForm[fieldName].focus();
			return false;
		 }
		 if (fieldName == "email" && !checkEmail(curForm.email.value))
		{
			alert(_alert_emailValid);
			curForm.email.focus();
			return false;
		 }
		 if (fieldName == "birthdate" && !isDate(curForm.birthdate.value))
		{
			alert(_alert_dateNotValid);
			curForm.birthdate.focus();
			return false;
		 }
 	}
 	if(curForm["password"].value != curForm["pwValidation"].value)
 	{
 			alert(_alert_noPwValidation);
			curForm.password.focus();
			return false;
 	}

	return confirm(_confirm_addNewUser);
}

function pwRemind()
{
	popupWin("popup_pwReminder.php", 340, 120);

}

function checkNumHoroscope(formID)
{
	f=document.getElementById(formID);
	if (f.birthdate.value=="")
	{
		alert (_alert_yourBirthdate);
		f.birthdate.focus();
		return false;
	}

	if(!isDate(f.birthdate.value))
	{
		alert (_alert_dateNotValid);
		return false;
	}
	else
		return true;
}

function checkNumCharacter(formID)
{
	f=document.getElementById(formID);
	if (f.name.value=="")
	{
		alert (_alert_yourName);
		f.name.focus();
		return false;
	}

	return true;
}

function checkNameCalc(formID)
{
	f=document.getElementById(formID);
	if (f.name.value=="")
	{
		alert (_alert_reqName);
		f.name.focus();
		return false;
	}

	return true;
}

function checkContact(formID)
{

	curForm=document.getElementById(formID);
	fArray=new Array("firstName","lastName","email","subject","body");

	for (i=0;i<fArray.length; i++)
	{
		fieldName = fArray[i];
		if (curForm[fieldName].value=="")
		{
			cMessage = eval("_alert_"+fieldName);
			alert(cMessage);
			curForm[fieldName].focus();
			return false;
		 }
		 if (fieldName == "email" && !checkEmail(curForm.email.value))
		 {
			alert(_alert_emailValid);
			curForm.email.focus();
			return false;
		 }
	}
	return confirm(_confirm_continue);
}
