// SYSTEM FUNCTIONS //
function openWindow(type,url) {
	var width, height, options;
	switch (type) {
		case "sendtofriend":
			width=400;
			height=500;
			options="scrollbars=1,resizable=1";
			break;
		default:
			width=800;
			height=600;
			options="scrollbars=1,resizable=1";
			break;
	}
	var top = window.screen.height/2-height/2;
	var left = window.screen.width/2-width/2;
	var win = window.open(url,type,"top="+top+",left="+left+",width="+width+",height="+height+","+options);
	win.opener = window;
	win.focus();
}

function printArticle() {
    if (window.print) window.print();
    else alert("Sorry, this feature is not available.\nPlease use your browser's print button.");
}
        
function sendToFriend(url) {
    url += "&pageurl=" + escape(window.location.href);
    openWindow('sendtofriend', url);
}

function validateSearchText() {
	var srchtxtbox = document.getElementById("searchtextbox");
	if (srchtxtbox.value == "") {
		alert("Please enter one or more search terms.");
		srchtxtbox.focus();
		return false;
	}
	return true;
}

function doSearch(searchpath) {
    if(validateSearchText()) {
        var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789- ";
        var searchText = "";
        var temp = document.getElementById('searchtextbox').value;
        for (i = 0; i < temp.length; i++)
            if (valid.indexOf(temp.charAt(i)) > -1)
                searchText += temp.charAt(i);
        window.location.replace(searchpath + '?q=' + searchText);
    }    
}

function onSearchEnter(evt, searchUrl) {
    var keyCode = null;
    if(evt.which)
        keyCode = evt.which;
    else if(evt.keyCode)
        keyCode = evt.keyCode;
    if(keyCode == 13) {
        doSearch(searchUrl);
        return false;
    }
    return true;
}

function GetCookie(name) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg)
			return getCookieVal(j);
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break;
	}
	return null;
}

function getCookieVal(offset) {
	var endstr = document.cookie.indexOf(";", offset);
	if (endstr == -1)
		endstr = document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

// TEMPLATE FUNCTIONS //
function bookmarkpage() {
	if (document.all) window.external.AddFavorite(window.location.href, document.title);
	else if (window.sidebar) window.sidebar.addPanel(document.title, window.location.href, "");
}

function sethomepage(object) {
	if (document.all && window.external) { // IE
		object.style.behavior = 'url(#default#homepage)';
		object.setHomePage(window.location.href);
	}	
	else
	  alert("This feature works best with Internet Explorer.\n\nTo manually set this page as your home page, copy the path in the address bar to your clipboard and paste it into the Home Page field in your browser preferences.");
}

function getDate() {
    var word_month = new Array( "January ", "February ", "March ", "April ", "May ", "June ", "July ", "August ", "September ", "October ", "November ", "December " )
    var right_now = new Date();
    var right_year=right_now.getYear();
    if (right_year < 2000) right_year = right_year + 1900;
    return word_month[right_now.getMonth()] + right_now.getDate()+", "+right_year;
}

function getTime() {
    var right_now = new Date();
    var time;
    var hours = right_now.getHours();
    if (hours>=12) time = "PM";
    else time = "AM";
    if (hours>12) hours -= 12;
    if (hours==0) hours = 12;
    var mins = right_now.getMinutes();
    if (mins<10) mins = "0" + mins;
    return hours+":"+mins+" "+time;
}

// FORM FUNCTIONS //
// TODO: Move these to forms so they're only loaded when needed
function submitForm(frmName) {
    // Get form
    var submitFormName = document.getElementById('submitFormName');
    if(submitFormName == null) return;
    submitFormName.value = frmName;
    
    // Validate required fields
    if (!validateRequiredFields(frmName)) {
        alert("Please answer all required questions.");
        return;
    }
    
    // Validate field formats
    if(!validateEmail(frmName, "EMAIL")) {
        alert("Invalid email address. Please use the format: name@domain.com");
        return;
    }
    if(!validateNumber(frmName, "HOMEAREA")) {
        alert("Invalid home phone area code. Please use the format: 123");
        return;
    }
    if(!validatePhoneNo(frmName, "HOMEPHONE")) {
        alert("Invalid home phone number. Please use the format: 123-4567");
        return;
    }
    if(!validateNumber(frmName, "MOBILEAREA")) {
        alert("Invalid mobile phone area code. Please use the format: 123");
        return;
    }
    if(!validatePhoneNo(frmName, "MOBILEPHONE")) {
        alert("Invalid mobile phone number. Please use the format: 123-4567");
        return;
    }
    if(!validateNumber(frmName, "FAXAREA")) {
        alert("Invalid fax phone area code. Please use the format: 123");
        return;
    }
    if(!validatePhoneNo(frmName, "FAXPHONE")) {
        alert("Invalid fax phone number. Please use the format: 123-4567");
        return;
    }
    if(!validateNumber(frmName, "WORKAREA")) {
        alert("Invalid work phone area code. Please use the format: 123");
        return;
    }
    if(!validatePhoneNo(frmName, "WORKPHONE")) {
        alert("Invalid work phone number. Please use the format: 123-4567");
        return;
    }
    
    // Submit form
    document.forms[0].submit();
}

function validateRequiredFields(frmName) {
    var frm = document.getElementById(frmName);
    var frmelements = frm.getElementsByTagName("input");
    for (var i = 0; i < frmelements.length; i++) {
        var field = frmelements[i];
        if (field.name.indexOf("_FW_REQ") > -1 && field.value == "on") {
            var name = field.name.replace(frmName + "_FW_REQ", "");
            var names = name.split("_");
            for (var j = 0; j < names.length; j++) {
                var ans = document.getElementsByName(frmName + "_" + names[j]);
                if(ans[0]) {
                    // Radio buttons
                    if (ans[0].type == 'radio') {
					    var hasVal = false;
                        for (var k = 0 ; k < ans.length; k++)
                           if (ans[k].checked) hasVal = true;
                        if(!hasVal) return false;
                    }
                    else if (ans[0].value == "") {
                        ans[0].focus();
                        return false;
                    }
                }
            }
        }
    }
    return true;
}

function validateEmail(frmName, elementName) {
    var emailField = document.getElementsByName(frmName + "_" + elementName);
    if (emailField[0] && emailField[0].value != "") {
        var format = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*\.([a-zA-Z0-9])+$/;
        var isValid = format.test(emailField[0].value);
        if(!isValid) emailField[0].focus();
        return isValid;
    }
    return true;
}

function validatePhoneNo(frmName, elementName) {
    var phoneField = document.getElementsByName(frmName + "_" + elementName);
    if (phoneField[0] && phoneField[0].value != "") {
        var format = /^\d{3}\-\d{4}$/;
        var isValid = format.test(phoneField[0].value);
        if(!isValid) phoneField[0].focus();
        return isValid;
    }
    return true;
}

function validateNumber(frmName, elementName) {
    var numField = document.getElementsByName(frmName + "_" + elementName);
    if (numField[0] && numField[0].value != "") {
        var format = /^\d+$/;
        var isValid = format.test(numField[0].value);
        if(!isValid) numField[0].focus();
        return isValid;
    }
    return true;
}

// GADGET FUNCTIONS //
function getGadgetURL(obj) {
    if(obj.src.indexOf("?") == -1) {
        obj.src += "?context=extend";
        if(login = GetCookie("extend_login"))
            obj.src += "&login=" + login;
    }
}

// PHOTOGALLERY FUNCTIONS //
// TODO: Move these to the photo gallery control so they're only loaded when needed
var slideshowDelay = 3000;
function viewGallery() {
    window.location.reload();
}

function viewAlbum(galleryID, albumID, startIndex, incrementCounter) {
    var url = '/controls/photogallery_loader.aspx?galleryid=' + galleryID + '&albumid=' + albumID + '&startindex=' + startIndex;
    if(incrementCounter)
        url += '&incrementcounter=1';
    AjaxRequest.get(
        {
            'url' : url,'onSuccess' : 
            function(req) { document.getElementById('ucPhotoGallery' + galleryID + '_spanPhotoGallery').innerHTML = req.responseText; },
            'onError' : function(req) { alert('Error! StatusText=' + req.statusText + 'Contents=' + req.responseText); }
        }
    )
}

function changeDelay(obj) {
    slideshowDelay = obj.options[obj.selectedIndex].value;
}

function viewPhoto(galleryID, albumID, photoID, inSlideshow) {
    var delay = 0;
    if(inSlideshow)
        delay = slideshowDelay;
    AjaxRequest.get(
        {
            'url' : '/controls/photogallery_loader.aspx?galleryid=' + galleryID + '&albumid=' + albumID + '&photoid=' + photoID + '&delay=' + delay,'onSuccess' : 
            function(req) { document.getElementById('ucPhotoGallery' + galleryID + '_spanPhotoGallery').innerHTML = req.responseText; },
            'onError' : function(req) { alert('Error! StatusText=' + req.statusText + 'Contents=' + req.responseText); }
        }
    )
}

function viewSlideshow(galleryID, albumID, photoID) {
    viewPhoto(galleryID, albumID, photoID, true)
    setTimeout('viewNextPhoto(' + galleryID + ', ' + albumID + ')', slideshowDelay);
}

function viewNextPhoto(galleryID, albumID) {
    var nextPhotoLink = document.getElementById('nextPhoto');
    if(nextPhotoLink) {
        window.location.replace(nextPhotoLink.href);
        setTimeout('viewNextPhoto(' + galleryID + ', ' + albumID + ')', slideshowDelay);
    }
    else if(document.getElementById('photo'))
        viewAlbum(galleryID, albumID, 0);
}

// CALENDAR FUNCTIONS //
// TODO: Move these to the calendar control so they're only loaded when needed
function adjustCalendar(calendarViewID, prePostDate, direction) {
    var workingDate = new Date(prePostDate);
    var day = workingDate.getDate();
    var month = workingDate.getMonth() + 1;
    var year = workingDate.getFullYear();

    if (direction == -1) {
        if (month == 1) {
            month = 12;
            year--;
        }
        else
            month--;
    }
    else if (direction == 1) {
        if (month == 12) {
            month = 1;
            year++;
        }
        else
            month++;
    }

    AjaxRequest.get(
        {
            'url':'/controls/calendarofevents_loader.aspx?CalendarViewID=' + calendarViewID + '&EventID=0&WorkingDate=' + month + '/01/' + year + '&Action=ShowCalendar'
            ,'onSuccess':function(req)
            {
                document.getElementById('ucCalendarOfEvents' + calendarViewID + '_spanCalendar').innerHTML = req.responseText;
            }
            ,'onError':function(req)
            {
                 alert('Error! StatusText=' + req.statusText + 'Contents=' + req.responseText);
            }
        }
    )
}

function showTodaysEvents(calendarViewID, eventDate) {
    var workingDate = new Date(eventDate);
    var day = workingDate.getDate();
    var month = workingDate.getMonth() + 1;
    var year = workingDate.getFullYear();
    
    AjaxRequest.get(
        {
            'url':'/controls/calendarofevents_loader.aspx?CalendarViewID=' + calendarViewID + '&EventID=0&WorkingDate=' + month + '/' + day + '/' + year + '&Action=ShowTodaysEvents'
            ,'onSuccess':function(req)
            {
                document.getElementById('ucCalendarOfEvents' + calendarViewID + '_spanCalendar').innerHTML = req.responseText;
            }
            ,'onError':function(req)
            {
                alert('Error! StatusText=' + req.statusText + 'Contents=' + req.responseText);
            }
        }
    )
}

function showEvent(calendarViewID, eventID, eventDate) {
    var workingDate = new Date(eventDate);
    var day = workingDate.getDate();
    var month = workingDate.getMonth() + 1;
    var year = workingDate.getFullYear();
    
    AjaxRequest.get(
        {
            'url':'/controls/calendarofevents_loader.aspx?CalendarViewID=' + calendarViewID + '&EventID=' + eventID + '&WorkingDate=' + month + '/' + day + '/' + year + '&Action=ShowEvent'
            ,'onSuccess':function(req)
            {
                document.getElementById('ucCalendarOfEvents' + calendarViewID + '_spanCalendar').innerHTML = req.responseText;
            }
            ,'onError':function(req)
            {
                alert('Error! StatusText=' + req.statusText + 'Contents=' + req.responseText);
            }
        }
    )
}