/***************** DATE VALIDATION ****************************/

var dtCh= "-";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	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 < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

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 );
}
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 isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	//var strDay=dtStr.substring(0,pos1)
	//var strMonth=dtStr.substring(pos1+1,pos2)
	//var strYear=dtStr.substring(pos2+1)

	var strYear=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strDay=dtStr.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 : dd/mm/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 || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date")
		return false
	}
return true
}

/**************************************************************/


function generateRandomString(length) 
{      
    var sStr = "";            
    
    for (i=0; i < length; i++) {
    
        numI = getRandomNum();        
        sStr = sStr + String.fromCharCode(numI);
    }
       
    return sStr;
}

function getRandomNum() {
        
    // between 0 - 1
    var rndNum = Math.random()

    // rndNum from 0 - 1000    
    rndNum = parseInt(rndNum * 1000);

    // rndNum from 33 - 127        
    rndNum = (rndNum % 94) + 33;
            
    return rndNum;
}

function navigate(url){
	document.location = url 
}

function openPopUp(sURL, lWinWidth, lWinHeigh)
{
	var t = (screen.availHeight-lWinHeigh)/2;
	var l = (screen.availWidth-lWinWidth)/2;
	var popUpWin = window.open(sURL, '', 'resizable=yes,scrollbars=yes,location=yes,menubar=yes,status=yes,toolbar=yes,width='+lWinWidth+',height='+lWinHeigh+',left='+l+',top='+t);
}

/*
Navigates to URL / Subchannel / Content Object / Media Item

sLinkType - Type of the content: U - URL, S - Subchannel, C - Content Object, M - Media Item
sURL - the URL. if sLinkType='U' - the URL, else - empty
lItemID - the ID of the subchannel, content object or media item. empty if sLinkType='U'
bIsNewWindow - 1 or ''
lWinHeight - the height of the new window
lWinWidth - the width of the new window
lCurrSubchannelID - the ID of the subchannel, where we pressed the link
*

function openLink(sLinkType, sURL, lItemID, bIsNewWindow, lWinWidth, lWinHeigh, lCurrSubchannelID)
{

	switch (sLinkType)
	{
		// link to URL
		case 'U':
		if (bIsNewWindow == 1)
			openPopUp(sURL, lWinWidth, lWinHeigh);
		else
			navigate (sURL);
		
		break;
		
		// link to Subchannel
		case 'S':
			navigate('DisplaySubchannel.jsp?lSubChannelID='+lItemID+'&lContentObjectID=-1&lMediaItemID=-1');
		break;
		
		// link to Content Object
		case 'C':
			navigate('DisplaySubchannel.jsp?lSubChannelID='+lCurrSubchannelID+'&lContentObjectID='+lItemID+'&lMediaItemID=-1');
		break;
		
		// link to media item
		case 'M':
			navigate('DisplaySubchannel.jsp?lSubChannelID='+lCurrSubchannelID+'&lContentObjectID=-1&lMediaItemID='+lItemID);		
		break;		
	}

}
*/
function openMediaItem(lMediaItemID)
{
	openPopUp('OpenMediaItem.jsp?lMediaItemID='+lMediaItemID,800,500);
}


/* checks the validation of email address
	
	Input: sEmail - the email
		   bEmptyValid - TRUE if empty string is a valid email, FALSE if not
		   
    Output:
    	   TRUE - email valid
    	   FALSE - email invalid
*/
function EmailCheck (sEmail, bEmptyValid)
 {

	var emailPat=/^(.+)@(.+)$/
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	var validChars="\[^\\s" + specialChars + "\]"
	var quotedUser="(\"[^\"]*\")"
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	var atom=validChars + '+'
	var word="(" + atom + "|" + quotedUser + ")"
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
	var matchArray=sEmail.match(emailPat)

	if ( (sEmail == '') && bEmptyValid ) {
		return true;
	}	

	if (matchArray==null) {
		//alert("Email address seems incorrect (check @ and .'s)")
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]

	//if (user.match(userPat)==null) {
	    // user is not valid
	    //alert("The username doesn't seem to be valid.")
	 //   return false
	//}

	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
	    // this is an IP address
		  for (var i=1;i<=4;i++) {
		    if (IPArray[i]>255) {
		        //alert("Destination IP address is invalid!")
			return false
		    }
	    }
	    return true
	}

	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		//alert("The domain name doesn't seem to be valid.")
	    return false
	}

	/* domain name seems valid, but now make sure that it ends in a
	   three-letter word (like com, edu, gov) or a two-letter word,
	   representing country (uk, nl), and that there's a hostname preceding 
	   the domain or country. */

	/* Now we need to break up the domain to get a count of how many atoms
	   it consists of. */
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 || 
	    domArr[domArr.length-1].length>3) {
	   // the address must end in a two letter or three letter word.
	   //alert("The address must end in a three-letter domain, or two letter country.")
	   return false
	}

	// Make sure there's a host name preceding the domain.
	if (len<2) {
	   var errStr="This address is missing a hostname!"
	   //alert(errStr)
	   return false
	}

	// If we've gotten this far, everything's valid!
	return true;
}


function GetCookie (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 SetCookie (name, value, expireDays, path, domain, secure) {

	var expireDate = new Date ();
	expireDate.setTime(expireDate.getTime() + (10000 * 24 * 3600 * 1000));

    document.cookie = name + "=" +escape(value) +
        ( (expireDate) ? ";expires=" + expireDate.toGMTString() : "") +
        ( (path) ? ";path=" + path : "") + 
        ( (domain) ? ";domain=" + domain : "") +
        ( (secure) ? ";secure" : "");
        
}

function DelCookie (name) 
{
	if (GetCookie(name)) 
		document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
}

function SetAutologinCookie()
{
	if (document.all.AutoLogin)
	{
		if (document.all.AutoLogin.checked)
			SetCookie('lExtUserID', document.all.UserID.value);
		else
			DelCookie('lExtUserID'); 
	}
}

function SetAutoLoginCheckbox()
{
//	if (GetCookie('lExtUserID') != '' && GetCookie('lExtUserID') != null)
//		document.all.AutoLogin.checked = true;

}

// opens full image preview (from thumbnail)
function OpenFullImage(sFilePath, sFileText)
{
	var h = 500;
	var w = 500;
	var t = (screen.availHeight-h)/2;
	var l = (screen.availWidth-w)/2;	
	
	var previewWin = window.open('../Ext/FullImagePreview.jsp?sFilePath='+sFilePath+'&sFileText='+sFileText,'prevWin','resizable=yes,scrollbars=yes,dependent=yes,width='+w+',height='+h+',left='+l+',top='+t);
}


// sets pivotal login session
function SetPivotalLogin (bPivotalLoginOK, sPivotalUserName, sPivotalUserFirstName, sPivotalUserLastName)
{	
	document.all.HiddenServiceIFrame.src = 'PerformPivotalLogin.jsp?bPivotalLoginOK=' + bPivotalLoginOK +
									   '&sPivotalUserName=' + sPivotalUserName +
									   '&sPivotalUserFirstName=' + sPivotalUserFirstName +
									   '&sPivotalUserLastName=' + sPivotalUserLastName;
									   
									  
	document.all.notLoggedIn.innerHTML = document.all.loggedIn.innerHTML;

}

function LogOffFromPivotal()
{
	document.all.HiddenServiceIFrame.src = 'PerformLogout.jsp?bFromPivotal=1';
}


function OpenCalendar(sFieldName,bIsClear)
{	
	var h = 210;
	var w = 280;
	var t = (screen.availHeight-h)/2;
	var l = (screen.availWidth-w)/2;
	var calWin = window.open('/Site/Resources/Elements/CalendarPopUp.jsp?sFieldName='+sFieldName+'&bIsClear='+bIsClear,'cal','dependent=yes,width='+w+',height='+h+',left='+l+',top='+t);
}
