
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Initialization
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
function onPageLoad() {
	/*
	var hotTopicDetails = document.getElementById("hot-issues-details-main");
	if (hotTopicDetails != undefined) {
		document.body.id = "hot-issues-details";
	}
	*/
	
    // Initialize the Banner
    if (document.getElementById("news-banner2")) {
        var m = new Ticker("news-banner2", 120, 4000);
       m.start();
  }

    // Initialize the Slide Show
    if (document.getElementById("slideShow")) {
        var s = new SlideShow("slideShow", 6000);
        s.addControls("slideshow-control-buttons", "slideshow-control-buttons",
                       [   "slideShowPrev",
                           "slideShowPlayIcon",
                           "slideShowStopIcon",
                           "slideShowNext"
                       ]);
        s.start();
    }
    
    // Initialize album slide show @ homepage albumShow
    if (document.getElementById("albumShowall")) {
        var h = new SlideShow("albumShowall", 6000);
        h.addControls("slideshow-control-buttons", "albumShowall-control-buttons",
                       [   "slideShowPrev",
                           "slideShowPlayIcon",
                           "slideShowStopIcon",
                           "slideShowNext"
                       ]);
        if (h.map.size() > 1) {
	        h.start();
	     }
    }
    
    // Initialize politics album slide show @ albums details pages
    if (document.getElementById("albumShowpolitics")) {
        var p = new SlideShow("albumShowpolitics", 6000);
        p.addControls("slideshow-control-buttons", "albumShowpolitics-control-buttons",
                       [   "slideShowPrev",
                           "slideShowPlayIcon",
                           "slideShowStopIcon",
                           "slideShowNext"
                       ]);
	   if (p.map.size() > 1)
	        p.start();                       
    }
    
    // Initialize art album slide show @ albums details pages
    if (document.getElementById("albumShowart")) {
        var a = new SlideShow("albumShowart", 6000);
        a.addControls("slideshow-control-buttons", "albumShowart-control-buttons",
                       [   "slideShowPrev",
                           "slideShowPlayIcon",
                           "slideShowStopIcon",
                           "slideShowNext"
                       ]);
    	if (a.map.size() > 1)
	        a.start();                       
    }
    
    // Initialize sports album slide show @ albums details pages
    if (document.getElementById("albumShowsports")) {
        var u = new SlideShow("albumShowsports", 6000);
        u.addControls("slideshow-control-buttons", "albumShowsports-control-buttons",
                       [   "slideShowPrev",
                           "slideShowPlayIcon",
                           "slideShowStopIcon",
                           "slideShowNext"
                       ]);
        if (u.map.size() > 1)
	        u.start();                       
    }
		
	// Initialize hotissues slide show @ home pages
    if (document.getElementById("hot-issues-slideshow")) {
        var h = new SlideShow("hot-issues-slideshow", 3000);       
        if (h.map.size() > 1)
	        h.start();                    
    }
    // Initialize the Make Us Your Home Page link
    makeUsYourHomePageLink = document.getElementById("home-page-bookmark");
    if (makeUsYourHomePageLink) {
        makeUsYourHomePageLink.onclick = makeUsYourHomePage;
    }

    // Initialize the Clock
    startClock();
    
    // Initializes any tree li tags
    initTreeItems();

    // IE6 for the button styles
    fixIE6ButtonStyles();
	
    // check for print ing the page
    var print = document.getElementById("printer-friendly-version");
    if (print && print != "undefined") {
        window.print();
    }
    
    //check for printing Livechat page
    var livechatPrint = document.getElementById("livechats-printer-friendly-version");
    if (livechatPrint && livechatPrint != "undefined") {
        window.print();
    }
    //check for printing ask the news page
    var askTheNewsPrint = document.getElementById("ask-the-news-printer-friendly-version");
    if (askTheNewsPrint && askTheNewsPrint != "undefined") {
        window.print();
    }
    //check for printing ask the news page
    var thisDayPrint = document.getElementById("this-day-in-history-printer-friendly-version");
    if (thisDayPrint && thisDayPrint != "undefined") {
        window.print();
    }
    
    

    // Initialize the window layout
//    windowLayout = document.getElementById("window");
//    containerDiv = document.getElementById("container");
//    //if (print && print != "undefined") containerDiv = null;
//    if (windowLayout && containerDiv) {
//        containerDiv.style.width = '100%';
//        containerDiv.style.margin = 0;
//        containerDiv.style.padding = 0;
//        containerDiv.style.background = 'none';
//    }
    
    // Initialize Polls
    initPolls();
    
    // Add video handlers
    var videoLinks = getElementsByClassName("video-link", "a");
    for (var i = 0; i < videoLinks.length; i++) {
        videoLinks[i].onclick = playVideo;
        videoLinks[i].style.zoom = "1"; /* fix disappering issue on small items on 
        the contnet main */
    }
	var videoLinks = getElementsByClassName("video-link2", "a");
    for (var i = 0; i < videoLinks.length; i++) {
        videoLinks[i].onclick = playVideo;
    }
    var disclaimerLinks = getElementsByClassName("disclaimer-link", "a");
    for (var i = 0; i < disclaimerLinks.length; i++) {
        disclaimerLinks[i].onclick = openDisclaimer;
    }
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") &&
		anchor.getAttribute("rel") == "external") {
			anchor.target = "_blank";
		}
	}
}

// Call the onPageLoad() when the page is loaded
addLoadEvent(function(){onPageLoad();})


function initTreeItems() {
    // Find all the <li> elements, to attach the event handlers to them
    var li = document.getElementsByTagName("li");
    for (var i = 0; i < li.length; i++ ) {
        // Attach a mouseover event handler to the <li> element,
        // which changes the <li>s background to blue.
        if (li[i].className.indexOf("nav-node") != -1) {
            /*
            if (li[i].className.indexOf("closed") == -1) {
                li[i].className = li[i].className + " closed";
            }
            */
            li[i].onclick = function(e) {
                var event = e || window.event;
                var target = event.target || event.srcElement;
                if (target.parentNode != this) return true;
                
                if (this.className.indexOf("closed") != -1) {
                    this.className = this.className.replace(" closed", "");
                } else {
                    this.className = this.className + " closed";
                }
                
                // If an event object is provided, then this is a non-IE browser
                if (e && e.stopPropagation) {
                    // and therefore it supports the W3C stopPropagation() method
                    e.stopPropagation();
                } else {
                    // Otherwise, we need to use the Internet Explorer
                    // way of cancelling event bubbling
                    window.event.cancelBubble = true;
                }
                return false;
            };
        }
    }
}

function makeUsYourHomePage() {
    makeUsYourHomePageLink = document.getElementById("home-page-bookmark");
    if (makeUsYourHomePageLink) {
        pathnameParts = window.location.pathname.split("/");
        appContext = "/" + pathnameParts[1];
        if (pathnameParts[1] == "wps") appContext += "/" + pathnameParts[2];
        appContext = appContext.replace("/myportal", "/portal");
        url = window.location.protocol + "//" + window.location.host + appContext + "/home";

        if (document.all) {
            makeUsYourHomePageLink.style.behavior = 'url(#default#homepage)';
            makeUsYourHomePageLink.setHomePage(url);
        } else if (isFireFox()) {
            alert('Drag this link onto your Home Page Icon to Make ' + url +' Your Homepage');
        } else {
            alert('Incompatible Browser');
        }
    }
    return false;
}


//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// General Application-specific functions
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

function showMessage(msgElement, msg) {
    if (msgElement.textContent) {
        msgElement.textContent = msg;
    } else {
        msgElement.innerText = msg;
    }
    msgElement.style.display = "block";
    return false;
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Polls
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

function initPolls() {
    // Check cookies to set poll's view visibilty, either show/hide normal or results view  
    // Validate poll's form
    var pollsBadgeForm = document.getElementById("polls-badge-form");//document.forms['polls-badge-form'];
    if (pollsBadgeForm) {
        cookieValue = getCookie(pollsBadgeForm.className);
        if (cookieValue != null) {
          setVisibility('pollsResults','block');
          setVisibility('pollsNormal','none');
          setVisibility('back-link','none');
        } 
        else {
          setVisibility('pollsResults','none');
          setVisibility('pollsNormal','block');
          setVisibility('back-link','block');
        }  
        pollBtn = document.getElementById("poll-btn")
        if (pollBtn) {
          //pollBtn.onclick = validatePollsForm(servletInvalidatorURL);      
          attachEventToComponent(pollBtn, 'click', validatePollsForm);
        }
        // Set poll's view visibilty on clicking Details link
        pollsDetailsLink = document.getElementById("polls-details-link");
        if (pollsDetailsLink) {
            pollsDetailsLink.onclick = function() {setVisibility('pollsResults','block');setVisibility('pollsNormal','none')};
        }    
        // Set poll's error message visibilty with default value "none"
        errMsg = document.getElementById("polls-err-msg");
        if(errMsg) {
        setVisibility(errMsg.id, 'none')
        }
        // Set poll's view visibilty on clicking back link
        backLink = document.getElementById("back-link");
        if (backLink) {
            backLink.onclick = function() {setVisibility('pollsResults','none');setVisibility('pollsNormal','block')};
        }           
    }
}

// Check selected option and cookie, if validations are fine invalidate polls and submit
function validatePollsForm(e) {
	e = e?e:window.event;
    formElement = document.getElementById("polls-badge-form")
    button = formElement.answer || formElement["answer"];
    count = -1;
    for (i = 0; i < button.length; i++) {
        if (button[i].checked) {
            count = i;
            break;
        }
    }
    exist = false;
    // Validate radio button group options
    if (count > -1) {
        exist = isCookieExist(formElement.className, 'qid');        
        setVisibility("polls-err-msg", 'none')
        if(!exist){
            url = document.getElementById("servletInvalidation").value;
            ajaxCall(url, 10);            
        }
        if (exist) stopEventProcessing(e);
        return (!exist);
    } else {
        setVisibility("polls-err-msg", 'block')
        stopEventProcessing(e);
        return false;
    }
}

function stopEventProcessing(evt){
	if(evt.preventDefault){
		evt.preventDefault();
	}
	if (evt.stopPropagation) {
		evt.stopPropagation();
	}
	evt.cancelBubble = true;
	evt.returnValue = false;
}

/*function validatePollsForm(cookieName, cookieValue, cookieMessage, formValidationMessage) {
    var form = document.getElementById("polls-badge-form");
    var button = form.answer || form["answer"];
    var count = -1;
    for (var i = 0; i < button.length; i++) {
        if (button[i].checked) {
            count = i;
            break;
        }
    }       
    var exist = false;
    if (count > -1) {
        exist = isCookieExist(cookieName, cookieValue, cookieMessage);
        return (!exist);
    } else {
        createMessage(formValidationMessage, 'pollsFormMessage');
        return false;
    }
}
*/ 

// Check the specified cookie's value if exist
function isCookieExist(name, value) {
    cookieValue = getCookie(name);
    if (cookieValue != null && cookieValue != "" && cookieValue == value) {
        return true;
    } else {
        days = 100;
        date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        setCookie(name, value, date);
        return false;
    }
}

// This function will create new div to display and validation message and append it in HTML div tag
function createMessage(messageText, tagId) {
    document.getElementById(tagId).innerHTML = messageText; 
}
    
// This function will set visibilty of Div in polls according to polls mode (normalview or resultsview)
function setVisibility(elementID, visibility) {
    document.getElementById(elementID).style.display = visibility;
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Search
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

function validateSearchForm(form, validationMessage) {
    var value = form.elements['searchText'].value;
    if (trim(value).length == 0) {
        alert(validationMessage);
        return false;
    }
    return true;
}

function validateDaySelection(day, month, year){
	if((month==2 || month==4 || month==6 || month==9 || month==11) && (day==31)){
		//alert("no 31");
		return false;
	}else if((month==2) && (day==30)){
		//alert("no 30 in feb.");
		return false;
	}else if(isNumber(year) && (month==2 && year%4!=0) && (day==29)){ // Leap years
		//alert("no 29 in feb.");
		return false;
	}
	return true;
}

function validateAdvancedSearchForm(form, keywordValidationMsg, dateValidationMsg, dateRangeMsg, dayValidationMsg) {
		var keyword = form.elements['query'].value;
		var dayStart = document.getElementById('dayStart').value;
    var monthStart = document.getElementById('monthStart').value;
    var yearStart = document.getElementById('yearStart').value;
    var dayEnd = document.getElementById('dayEnd').value;
    var monthEnd = document.getElementById('monthEnd').value;
    var yearEnd = document.getElementById('yearEnd').value;
		
		//keyword not empty
    if (trim(keyword).length == 0) {
    	alert('\t'+keywordValidationMsg+'\t');
      return false;
    }
    //pub date validation
    if( (isNumber(dayStart) && (!isNumber(monthStart) || !isNumber(yearStart))) 
    	|| (isNumber(monthStart) && (!isNumber(dayStart) || !isNumber(yearStart)))
    	|| (isNumber(yearStart) && (!isNumber(dayStart) || !isNumber(monthStart))) ){
    	alert('\t'+dateValidationMsg+'\t');
    	return false;
    }
    if( (isNumber(dayEnd) && (!isNumber(monthEnd) || !isNumber(yearEnd))) 
    	|| (isNumber(monthEnd) && (!isNumber(dayEnd) || !isNumber(yearEnd)))
    	|| (isNumber(yearEnd) && (!isNumber(dayEnd) || !isNumber(monthEnd))) ){
    	alert(dateValidationMsg+'\t');
    	return false;
    }
    
    if(isNumber(dayStart) && isNumber(monthStart) && isNumber(yearStart)
    	&& !validateDaySelection(dayStart, monthStart, yearStart)){
    	alert(dayValidationMsg);
    	return false;
    }
    
   	if(isNumber(dayEnd) && isNumber(monthEnd) && isNumber(yearEnd)
    	&& !validateDaySelection(dayEnd, monthEnd, yearEnd)){
    	alert(dayValidationMsg);
    	return false;
    }
    
    //make sure start date is before end date, if both are given
    if(isNumber(dayStart) && isNumber(monthStart) && isNumber(yearStart)
    	 && isNumber(dayEnd) && isNumber(monthEnd) && isNumber(yearEnd)){
    	
    	var fromDate = new Date();
    	fromDate.setFullYear(yearStart, monthStart-1, dayStart);
    	var toDate = new Date();
			toDate.setFullYear(yearEnd, monthEnd-1, dayEnd);
			
			if (Date.parse(fromDate) > Date.parse(toDate)) {
				alert(dateRangeMsg+'\t');
				return false;
			}
    }
    
    return true;
}

function clearText(elementId){
		var textValue = document.getElementById(elementId).value;
		
		if( !isNumber(textValue) ){
			document.getElementById(elementId).value = "";
		}
		
}

function isNumber(value){
	if( value != "" && value == parseInt(value) ){
		return true;
	}
	return false;
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Content Details, Send to a friend and Printer Friendly version
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

function validateCommentsForm(msg, msg_length) {
    var err = document.getElementById("error-msg");
    var commentsForm = document.getElementById("comments-form");
    
    if(formIsBusy(commentsForm)){
		return false;
    }
    
    if(commentsForm.comment.value != '' && commentsForm.comment.value.length > 600){
    	return showMessage(err, msg_length);
    } else if (commentsForm.username.value == '' || commentsForm.comment.value == '') {
        return showMessage(err, msg);
    } else {
        setBusyForm(commentsForm);
    	return true;
    }
}

function validateCommentLength(msg_length, length){
	var err = document.getElementById("error-msg");
    var commentsForm = document.getElementById("comments-form");
    length = length || 600;
    if(commentsForm.comment.value.length > length){
    	return showMessage(err, msg_length);
    } else{
    	return true;
    }
}
//create this function
String.prototype.count=function(s1) { 
	return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
}

function textCounter(fieldname, cntfieldname, maxlimit) {
	var field = document.getElementById(fieldname);
	var cntfield = document.getElementById(cntfieldname);
//	alert("\\n: " + field.value.count('\n'));
//	alert("\\r: " + field.value.count('\r'));
	if ((field.value.length + field.value.count('\n') - field.value.count('\r')) > maxlimit){ // if too long...trim it!
		field.value = field.value.substring(0, maxlimit - field.value.count('\n') + field.value.count('\r'));
	} else{ // otherwise, update 'characters left' counte
		cntfield.value = maxlimit - field.value.length - field.value.count('\n') + field.value.count('\r');
	}
}

function sendMail(path) {
    window.open(path, "_blank", "width=500,height=450,scrollbars=yes,toolbar=no,location=no");
    return false;
}

function validateNullOrEmpty(field, errorMsg) {
    var err = document.getElementById("error-msg");
    if (!(field && field.value && field.value != null && field.value != '')) {
        showMessage(err, errorMsg);
        if (field.focus) field.focus();
        return true;
    } else {
        err.style.display = "none";
        return false;
    }
}

function validateMailAddress(field, errorMsg) {
    var at="@"
    var dot="."
    str = field.value;
    var lat = str.indexOf(at)
    var lstr = str.length-1
    var ldot = str.indexOf(dot)
    var isValid = true;
    if (str.indexOf(at) == -1) {
        isValid = false
    }
    if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
        isValid = false;
    }
    if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
        isValid = false;
    }
    if (str.indexOf(at, lat + 1) != -1) {
        isValid = false;
    }
    if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) {
        isValid = false;
    }
    if (str.indexOf(dot,lat + 2) == -1) {
        isValid = false;
    }
    if (str.indexOf(" ") != -1) {
        isValid = false;
    }
    var err = document.getElementById("error-msg");
    if (isValid == false) {
        showMessage(err, errorMsg);
        if (field.focus) field.focus();
        return false;               
    } else {
        err.style.display = "none";
        return true;                    
    }
}

function playVideo() {
    window.open(this.href, "_blank", "width=400,height=320,scrollbars=yes,toolbar=no,location=no");
    return false;
}
function openDisclaimer() {
    window.open(this.href, "_blank", "width=800,height=400,scrollbars=yes,toolbar=no,location=no");
    return false;
}

function printFriendlyVersion(path) {             
    var printWindow = window.open(path, "_blank");
//    printWindow.print();
    return false;
}

// Used to validate the length of users comments
function imposeMaxLength(Object, MaxLen) {
  return (Object.value.length <= MaxLen);
}


//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// HelpDesk
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

function validateHelpDeskForm(msg_all, msg_name, msg_email, msg_emailFormat, msg_question) {
    var err = document.getElementById("error-msg");
    var helpDeskForm = document.getElementById("helpDeskForm");
    
    if(formIsBusy(helpDeskForm)){
		return false;
    }

    if (helpDeskForm.name.value == '' && helpDeskForm.email.value == '' && helpDeskForm.messageText.value == '') {
        return showMessage(err, msg_all);
    } else if (helpDeskForm.name.value == '') {
        return showMessage(err, msg_name);
    } else if (helpDeskForm.email.value == '') {
        return showMessage(err, msg_email);
    } else if (!validateMailAddress(helpDeskForm.email, msg_emailFormat)) {
        return false;
    } else if (helpDeskForm.messageText.value == '') {
        return showMessage(err, msg_question);
    }
    
    setBusyForm(helpDeskForm);
    return true;
}


//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Login and Registration
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

function validateLoginForm(msg_all, msg_name, msg_pwd) {
    var err = document.getElementById("error-msg");
    var loginForm = document.getElementById("loginForm");
    
    if(formIsBusy(loginForm)){
		return false;
    }

    if (loginForm.userName.value == '' && loginForm.pwd.value == '') {
        return showMessage(err, msg_all);
    } else if (loginForm.userName.value == null || loginForm.userName.value == '') {
        return showMessage(err, msg_name);
    } else if (loginForm.pwd.value == null || loginForm.pwd.value == '') {
        return showMessage(err, msg_pwd);
    }
    
    setBusyForm(loginForm);
    return true;
}

function validateRegistrationForm(msg_name, msg_name_format, msg_name_length, msg_pass, msg_pass_length, msg_pass_format, msg_passConfrim, msg_passNE,
        msg_email, msg_wrong_email) {
    var err = document.getElementById("error-msg");
    var registrationForm = document.getElementById("registrationForm");
    
    if(formIsBusy(registrationForm)){
		return false;
    }
       
    if (registrationForm.userName.value == null || registrationForm.userName.value == '') {
        return showMessage(err, msg_name);
    } else if ( /[^A-Za-z0-9.-_]/.test(registrationForm.userName.value) || /[!@#$%^&*\(\)+=?<>\]\[\/\\]/.test(registrationForm.userName.value) ) {
        return showMessage(err, msg_name_format);
    } else if (registrationForm.userName.value.length < 6 || registrationForm.userName.value.length > 20) {
        return showMessage(err, msg_name_length);
    } else if (registrationForm.pass.value == null || registrationForm.pass.value == '') {
        return showMessage(err, msg_pass);
    } else if (registrationForm.pass.value.length < 6 || registrationForm.pass.value.length > 20) {
        return showMessage(err, msg_pass_length);
    } else if ( /[^A-Za-z0-9.-_]/.test(registrationForm.pass.value) || /[!@#$%^&*\(\)+=?<>\]\[\/\\]/.test(registrationForm.pass.value) ) {
        return showMessage(err, msg_pass_format);
    } else if (registrationForm.passConfrim.value == null || registrationForm.passConfrim.value == '') {
        return showMessage(err, msg_passConfrim);
    } else if (registrationForm.pass.value != registrationForm.passConfrim.value) {
        return showMessage(err, msg_passNE);
    } else if (registrationForm.email.value == null || registrationForm.email.value == '') {
        return showMessage(err, msg_email);
    } else if (registrationForm.email.value != null && registrationForm.email.value != '') {
        atpos = registrationForm.email.value.indexOf("@");
        dotpos = registrationForm.email.value.lastIndexOf(".");
        if (atpos < 1 || dotpos - atpos < 2) {
            return showMessage(err, msg_wrong_email);
        }
    }

    newsLetter = document.getElementById('susbcribeInNews');
    if (newsLetter.checked) {
    	newsLetter.value = "true";
    }else{
    	newsLetter.value = "false";
    }
    
    setBusyForm(registrationForm);
    return true;
}

function validateForgotPasswordForm(msg_empty_email, msg_wrong_email) {
    var err = document.getElementById("error-msg");
    var forgotPasswordForm = document.getElementById("forgotPasswordForm");
    
    if(formIsBusy(forgotPasswordForm)){
		return false;
    }
     	
    if (forgotPasswordForm.email.value == null || forgotPasswordForm.email.value == '') {
        return showMessage(err, msg_empty_email);
    } else if (forgotPasswordForm.email.value != null && forgotPasswordForm.email.value != '') {
        atpos = forgotPasswordForm.email.value.indexOf("@");
        dotpos = forgotPasswordForm.email.value.lastIndexOf(".");
        if (atpos < 1 || dotpos - atpos < 2) {
            return showMessage(err, msg_wrong_email);
        }
    }

    setBusyForm(forgotPasswordForm);
    return true;
}

function validateSendMailForm(msg_emptyTo, msg_emptyToMail, msg_invalidToEMail, msg_emptyFrom, msg_emptyFromMail, msg_invalidFromEMail, msg_emptySubject, url) {
	var sendMailForm = document.getElementById("sendMailForm");
	var err = document.getElementById("error-msg");
	
	if(formIsBusy(sendMailForm)){
		return false;
    }
	
	if(!(validateNullOrEmpty(sendMailForm.toName, msg_emptyTo)) && 
	   !(validateNullOrEmpty(sendMailForm.toMail, msg_emptyToMail)) &&
	   (validateMailAddress(sendMailForm.toMail, msg_invalidToEMail))&&
	   !(validateNullOrEmpty(sendMailForm.fromName, msg_emptyFrom)) &&
	   !(validateNullOrEmpty(sendMailForm.fromMail, msg_emptyFromMail)) &&
	   (validateMailAddress(sendMailForm.fromMail, msg_invalidFromEMail))&&
	   !(validateNullOrEmpty(sendMailForm.subject, msg_emptySubject))) {
	    
		var pageUrl = document.getElementById("page-url");
	    if(pageUrl != null) {
	  	    var val = window.location.protocol + "//" + window.location.host + url;
     	  	pageUrl.value = val;
        }
        
        setBusyForm(sendMailForm);
        return true;
	}
	return false;
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Library
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

function showhide(targetID) {
    var elementmode = document.getElementById(targetID).style;
    elementmode.display = (!elementmode.display) ? 'none' : '';
}

    function setLibraryAction(submitHiddenField, submitValue, message){
      clearErrorMessage();
      document.getElementById(submitHiddenField).value = submitValue;
      if(submitValue=='search'){
        if(validateSearchInput()){
          return true;
        }else{
          showErrorMessage(message);
          return false;
      }
      }else if(submitValue=='save'){
          if( validateLibraryFields()){
              return true;
          }else{
              showErrorMessage(message);
              return false;
          }    
      }else if(submitValue=='reset'){
      	return confirm(message);
      }
    }
    
    function validateSearchInput(){
      searchKeyword = document.getElementById('authorSearchKeyword') ;
      if(searchKeyword != undefined && searchKeyword != null && searchKeyword.value != '' ){
        return true;
      }
      return false;
    }

    function validateLibraryFields(){
      // validate title
      docTitle = document.getElementById('title') ;       
      if(( docTitle != undefined && docTitle != null && docTitle.value != '')){
		var title = docTitle.value;
		title = trimString(title);
		if(title == '' || title.length == 0){      
          return false;  
        }
      }else {
		return false;
	}
      
      // validate summary
      docSummary =  document.getElementById('abstract') ;
      if(docSummary != undefined && docSummary != null && docSummary.length != 0 && docSummary.value != ''){    
        var summary = docSummary.value;
      	summary = trimString(summary);
        if(summary == '' || summary.length == 0){      
          return false;  
        }
      }else {   
        return false;  
      }
      
      // validate authors
      // docAuthors =  document.getElementById('authors');
      // oneSelected = false;
      // if( docAuthors != undefined && docAuthors != null && docAuthors.length != 0 ){
      //     for(j = 0; j < docAuthors.length; ++j){
      //       if(docAuthors.options[j].selected){
      //         oneSelected = true;
      //       }
      //     }
      // }
      // if(!oneSelected){
      //       return false;
      // }
      
      // validate categories
      docCategory = document.getElementsByName('categories') ;
      oneChecked = false;
      if( docCategory != undefined && docCategory != null && docCategory.length != 0 ){
        for(i = 0; i < docCategory.length; ++i) {   
          if (docCategory[i].checked == 1) {
            oneChecked = true;
          }
        }
      }
      return oneChecked;
    }
    
    function trimString(str){
		str = str.replace(/^\s+/,'').replace(/\s+$/,'');
		return str;
	}

    function clearErrorMessage(){
      document.getElementById("error-message").value='';
      document.getElementById("error-message").style.visibility='hidden';
      document.getElementById("message").style.visibility='hidden';
      return;
    }
    
    function showErrorMessage(message){
      document.getElementById("error-message").value = message;
      document.getElementById("error-message").style.visibility='visible';
      document.getElementById("error-message").focus();
      document.getElementById("message").style.visibility='hidden';
      return;
    }

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Clock
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

// Get the arabic name for the day
var weekday = new Array(7);
weekday[0] = "\u0627\u0644\u0623\u062D\u062F";
weekday[1] = "\u0627\u0644\u0623\u062B\u0646\u064A\u0646";
weekday[2] = "\u0627\u0644\u062B\u0644\u0627\u062B\u0627\u0621"
weekday[3] = "\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621";
weekday[4] = "\u0627\u0644\u062E\u0645\u064A\u0633";
weekday[5] = "\u0627\u0644\u062C\u0645\u0639\u0629";
weekday[6] = "\u0627\u0644\u0633\u0628\u062A";
var cairozone = "\u0628\u062A\u0648\u0642\u064A\u062A \u0627\u0644\u0642\u0627\u0647\u0631\u0629";

function startClock() {
    var clock = document.getElementById("clock");
    if (clock == null) return;

    // Retrieve the Cairo Time Zone offset as provided by the server (in milli-seconds)
    var cairoOffset = parseInt(clock.className);
    
    // Get the time on the local machine date
    var ld = new Date();
    
    // Retrieve the Local Time Zone offset (the Javascript offset is in minutes) and opposite sign (Cairo is -120)
    var localOffset = - (ld.getTimezoneOffset() * 60000);
    
    // create new Date object for Cairo time
    // offset the value by the difference between the Cairo Time Zone and the Local Time Zone
    cd = new Date(ld.getTime() + (cairoOffset - localOffset));
   
    document.getElementById("current-date").innerHTML = weekday[cd.getDay()] + " " + cd.getDate() + "/" + (cd.getMonth()+1) + "/" + cd.getFullYear();
    document.getElementById("current-time").innerHTML = cd.getHours() + ":" + checkTime(cd.getMinutes())  + " " + cairozone;

    // Re-call the function each 30 seconds
    t = setTimeout('startClock()', 30000);
}

// used to add zero in front of minutes in case < 10
function checkTime(i) {
    if (i < 10) {
        return "0" + i;
      } else {
        return i;
 }
}
function validateLiveChatQaForm(name_err, question_err, question_err_len){
	return validateNameAndQuestion(name_err, question_err, question_err_len);		
}
function validateNameAndQuestion(name_err, question_err, question_err_len) {
	var senderName = document.getElementById("name");
	var questionTxt = document.getElementById("question");
	var errorField = document.getElementById("error-msg");	
	
	if(senderName != undefined && senderName.value != undefined && senderName.value == "") {
		return showMessage(errorField, name_err);		
 	} else if (/\S+/.test(senderName.value) == false) {
 			return showMessage(errorField, name_err);	
	 }
	if(questionTxt != undefined && questionTxt.value != undefined ) {
		if (questionTxt.value == null || questionTxt.value == "") {
				return showMessage(errorField, question_err);
	 	 } else if (questionTxt.value.length > '300' ) {
				return showMessage(errorField, question_err_len);
	 	} else if (/\S+/.test(questionTxt.value) == false) {
			 	return showMessage(errorField, question_err);
		 }
	} 			 									
	return true;
}
function getStyle(x,styleProp){
	if (x.currentStyle) {
		var y = x.currentStyle[styleProp];
	} else if (window.getComputedStyle) {
		var y = document.defaultView.getComputedStyle(x, null)[styleProp];
	}
	return y;
}
function getHeight(obj){
	var borderWidth = parseFloat(getStyle(obj, "borderTopWidth")) + 
					parseFloat(getStyle(obj, "borderBottomWidth"));
	var paddingY = parseFloat(getStyle(obj, "paddingTop")) + 
					parseFloat(getStyle(obj, "paddingBottom"));
	var ret = parseFloat(obj.offsetHeight);
	if (borderWidth){
		ret = ret - (borderWidth + paddingY);
	}
	return  ret;
}

function showChatTerms() {
	var div = document.getElementById("live-chat-terms");
	var bgDiv = document.createElement("div");
	bgDiv.style.width = "100%";
	bgDiv.style.height = getHeight(document.body) + "px";
	bgDiv.style.backgroundColor = "#000";
	bgDiv.style.filter = "alpha(opacity=50)";
	bgDiv.style.opacity = 0.5;
	bgDiv.style.zIndex = 99;
	bgDiv.style.position = "absolute";
	bgDiv.style.top = 0;
	div.style.display = "block";
	document.body.appendChild(bgDiv);
	bgDiv.onclick = function(e) {
		this.style.display = "none";
		div.style.display = "";
	}
}

function adjustFormURL(form, url, msg){
	var month = document.getElementById('Month').value;
	var dayOfMonth = document.getElementById('Day').value;
	
	if(month == "" || dayOfMonth == "" || !validateDaySelection(dayOfMonth, month, "")){
		alert(msg);
		return false;
	}else{
		form.action = url +  (Number(month * 100) + Number(dayOfMonth));
		return true;
	}
}

function loadChildren(children, allMsg){
  var selectedParentId = document.getElementById('parentCategory').value;
  
	//clear all children first
	document.getElementById('childCategory').length = 0;
	document.getElementById('allChildren').length = 0;
	
	if( children.length > 0 ){
		document.getElementById('childCategory').disabled = false;
		document.getElementById('childCategory').options.add(new Option(allMsg, "none"));

	  //alert("children.length==="+children.length);
	  
	  var count = 0;
	  for(var i=0 ; i<children.length ; i++ ){
	  	
	  	if( selectedParentId == children[i][0] ){
				var child = children[i][1];
	  		var separatorIndex = child.indexOf('_');
	  		var value = child.substring(0, separatorIndex);
	  		var name = child.substring(separatorIndex+1);
	  		document.getElementById('childCategory').options.add(new Option(name, value));
	  		document.getElementById('allChildren').options.add(new Option("catIds", value));
	  		document.getElementById('allChildren').options[count].selected = true;
	  		count++;
	  	}
	  }
	}else{
		document.getElementById('childCategory').disabled = 'disabled';
	}
	return true;
}
