var pageClientID = "mainMaster_mainContent_";

// trim the value to get rid of spaces
String.prototype.trim = function(){
    return this.replace(/^\s+|\s+$/g, '');
}

// replaces all instances of the given substring.
String.prototype.replaceAll = function(replaceText, replaceWith) {
    var strText = this;
    var intIndexOfMatch = strText.indexOf(replaceText);

    while (intIndexOfMatch != -1) {
        strText = strText.replace(replaceText, replaceWith)
        intIndexOfMatch = strText.indexOf(replaceText);
    }

    return (strText);
}

// determines if the specified value exists in an Array object
Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
}

// Returns a random number between min and max   
function getRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Returns an array of unique random numbers between min and max
function getUniqueRandomNumbers(min, max, count) {
    if (count > (max - min + 1)) return null;

    var arr = new Array();

    while (arr.length < count) {
        var randomNumber = getRandomNumber(min, max);
        var found = false;
        
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] == randomNumber) {
                found = true;
                break; 
            }
        }

        if (!found) arr.push(randomNumber);
    }

    return arr;
}

function openCourseWindow(theURL,winName,features) {
  window.open(theURL,winName,features);
}

function isStrongPassword(value)
{
    // password checker regular expression
    //var strongPasswordRegex = new RegExp("^(?=.{8,15})((?=.*[a-zA-Z])((?=.*[0-9]{1,})|(?=.*\\W{1,}))|(?=.*[0-9])((?=.*[a-zA-Z]{1,})|(?=.*\\W{1,}))).*$", "g");
    //var pattern = "^(?=.{8,15})(?!.*\s)((?=.*[a-zA-Z])((?=.*[0-9]{1,})|(?=.*\\W{1,}))|(?=.*[0-9])((?=.*[a-zA-Z]{1,})|(?=.*\\W{1,}))).*$";
    
    var pattern = "^(?=.{8,15})(?!.*\\s)((?=.*[a-zA-Z])((?=.*[0-9]{1,})|(?=.*\\W{1,}))|(?=.*[0-9])((?=.*[a-zA-Z]{1,})|(?=.*\\W{1,}))).*$";
    var strongPasswordRegex = new RegExp(pattern, "g");
    
    return strongPasswordRegex.test(value);
}

function ratePassword(txtObjID, imgObjID)
{
    var txtObj = document.getElementById(txtObjID);
    var imgObj = document.getElementById(imgObjID);
    var password = txtObj.value.trim();
    
    if (password == "")
    {
        imgObj.src = "/images/password/password_unrated.gif";
    }
    else
    {
        if (isStrongPassword(password))
        {
            imgObj.src = "/images/password/password_met.gif";
        }
        else
        {
            imgObj.src = "/images/password/password_not_met.gif";
        }
    }
}

function defaultSearch(obj)
{
    //if (obj.value == "") obj.value = "Ask a Question";
}

function autoResizeIframe(frameID) 
{
    if (!window.opera && document.all && document.getElementById) {
        parent.document.getElementById(frameID).style.height = this.document.body.offsetHeight + "px";
    }
    else if (document.getElementById) {
        parent.document.getElementById(frameID).style.height = this.document.body.scrollHeight + "px";
    }
}

function swapImage(obj) {
    if (obj == null) return;

    if (obj.src.indexOf("_over.gif") != -1)
        obj.src = obj.src.replace("_over.gif", ".gif");
    else
        obj.src = obj.src.replace(".gif", "_over.gif");
}

// function to highlight form element
function hilite(obj) 
{
    var hiliteColor = "#FFF8E1";
    var defaultColor = "#FFFFFF";
    var element = obj;
    var type = element.type;

    if (type == "checkbox" || type == "radio") 
    {
        //element.style.backgroundColor = (element.checked == true) ? hiliteColor : defaultColor;
    }
    else if (type == "text" || type == "textarea") 
    {
        element.style.backgroundColor = (element.value.trim() != "") ? hiliteColor : defaultColor;
    }
    else if (type == "select-one" || type == "select-multiple") 
    {
        var isSelected = false;
        
        for (var i = 0; i < element.options.length; i++) 
        {
            if (element.options[i].selected && element.options[i].value != "") 
            {
                isSelected = true;
                break;
            }
        }
        
        element.style.backgroundColor = (isSelected == true) ? hiliteColor : defaultColor;
    }
}

// determines whether a date is valid (Ex. mm/dd/yyyy)
function isValidDate(strValue) {
    var objRegExp = /^\d{1,2}(\/)\d{1,2}\1\d{4}$/

    if (!objRegExp.test(strValue))
        return false; // doesn't match pattern
    else {
        var arrayDate = strValue.split(RegExp.$1); //split date into month, day, year
        var intDay = parseInt(arrayDate[1], 10);
        var intYear = parseInt(arrayDate[2], 10);
        var intMonth = parseInt(arrayDate[0], 10);

        // check for valid month
        if (intMonth > 12 || intMonth < 1) {
            return false;
        }

        // create a lookup for months not equal to Feb.
        var arrayLookup = { '01': 31, '03': 31, '04': 30, '05': 31, '06': 30, '07': 31, '08': 31, '09': 30, '10': 31, '11': 30, '12': 31 }

        arrayDate[0] = arrayDate[0].pad(2, '0', 0);
        
        // check if month value and day value agree
        if (arrayLookup[arrayDate[0]] != null) {
            if (intDay <= arrayLookup[arrayDate[0]] && intDay != 0)
                return true;
        }

        // check for February
        var isLeapYear = (intYear % 4 == 0 && (intYear % 100 != 0 || intYear % 400 == 0));
        if (((isLeapYear && intDay <= 29) || (!isLeapYear && intDay <= 28)) && intDay != 0)
            return true;
    }

    return false;
}

// returns current date;
function getCurrentDate() {
    var today = new Date();

    return (today.getMonth() + 1) + "/" + today.getDate() + "/" + today.getFullYear();
}

// Returns the string with a substring padded on the left, right or both sides. 
// length amount of characters that the string must have 
// substring string that will be concatenated 
// type specifies the side where the concatenation will happen, where: 0 = left, 1 = right and 2 = both sides
String.prototype.pad = function(l, s, t) {
    return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
        + 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
        + this + s.substr(0, l - t) : this;
};

// returns the left position for a given element
function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    }
    else if (obj.x)
        curleft += obj.x;
    return curleft;
}

// returns the top position for a given element
function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}

// Displays the Context Sensitive/Narrative Help for the appropriate fields
/*
function showHelp(obj) {
    var hlpDiv = obj;
    var hlpContents = document.getElementById(obj.id + "Contents");
    //var hlpFrame = document.getElementById(obj.id + "Frame");
    var hlpFrame = document.createElement("IFRAME");

    hlpFrame.setAttribute("id", hlpDiv.id + "Frame");
    hlpFrame.setAttribute("frameborder", "0");
    hlpFrame.setAttribute("scrolling", "no");
    hlpFrame.style.position = "relative";

    hlpFrame.style.left = 0;
    hlpFrame.style.top = 0;
    hlpFrame.style.width = hlpContents.clientWidth;
    hlpFrame.style.height = hlpContents.clientHeight;
    hlpFrame.style.zIndex = hlpDiv.style.zIndex - 1;

    hlpDiv.appendChild(hlpFrame);

    hlpContents.style.left = 0;
    hlpContents.style.top = 0;
    hlpContents.style.zIndex = hlpDiv.style.zIndex;

    hlpDiv.style.width = hlpContents.clientWidth;
    hlpDiv.style.height = hlpContents.clientHeight;

    obj.style.visibility = "visible";
}
*/

// Hides the Context Sensitive/Narrative Help for the appropriate fields
/*
function hideHelp(obj) {
    var hlpDiv = obj;
    var hlpFrame = document.getElementById(obj.id + "Frame");

    if (hlpFrame != null) hlpDiv.removeChild(hlpFrame);
    obj.style.visibility = "hidden";
}
*/

var hideDelay = 200;
var hideTimer = null;
// Displays the Context Sensitive/Narrative Help for the appropriate fields
function showHelp(obj) {
    if (hideTimer)
	    clearTimeout(hideTimer);

    var hlpDiv = obj;
    var hlpContents = document.getElementById(obj.id + "Contents");
    //var hlpFrame = document.getElementById(obj.id + "Frame");
    var hlpFrame = (document.getElementById(obj.id + "Frame") != null) ? document.getElementById(obj.id + "Frame") : document.createElement("IFRAME");

    hlpFrame.setAttribute("id", hlpDiv.id + "Frame");
    hlpFrame.setAttribute("frameborder", "0");
    hlpFrame.setAttribute("scrolling", "no");
    hlpFrame.style.position = "relative";

    hlpFrame.style.left = 0;
    hlpFrame.style.top = 0;
    hlpFrame.style.width = hlpContents.clientWidth;
    hlpFrame.style.height = hlpContents.clientHeight;
    hlpFrame.style.zIndex = hlpDiv.style.zIndex - 1;

    hlpDiv.appendChild(hlpFrame);

    hlpContents.style.left = 0;
    hlpContents.style.top = 0;
    hlpContents.style.zIndex = hlpDiv.style.zIndex;

    hlpDiv.style.width = hlpContents.clientWidth;
    hlpDiv.style.height = hlpContents.clientHeight;

    hlpDiv.onmouseover = function() {
	    if (hideTimer)
	        clearTimeout(hideTimer);
    };

    hlpDiv.onmouseout = function() {
        hideHelp(obj);
    }

    obj.style.visibility = "visible";
}

// Hides the Context Sensitive/Narrative Help for the appropriate fields
function hideHelp(obj) {
    if (hideTimer)
	    clearTimeout(hideTimer);

	hideTimer = setTimeout(function() {
        var hlpDiv = obj;
        var hlpFrame = document.getElementById(obj.id + "Frame");

        if (hlpFrame != null) hlpDiv.removeChild(hlpFrame);
        
        obj.style.visibility = "hidden";
    }, hideDelay);
}


function terms(url) {
    window.open(url, "terms", "width=400,height=400,scrollbars,resizable")
}

function trademark(url) {
    window.open(url, "trademark", "width=350,height=350,scrollbars,resizable")
}

function privacy() {
    window.open("/includes/privacy.asp", "privacy", "width=350,height=350,scrollbars,resizable")
}

function logout() {
    var hostName = window.location.hostname;
    var serverName = "";

    if (hostName.toLowerCase().indexOf('test') != -1) {
        serverName = "sfconnectiontest.advent.com";
    }
    else if (hostName.toLowerCase().indexOf('dev') != -1) {
        serverName = "vmconnectiondev.advent.com";
    }
    else {
        serverName = "connection.advent.com";
    }

    window.location.href = "http://" + serverName + "/km/logout.jsp";
}

// Converts a given UTC DateTime to User's TimeZone
// SAMPLE INPUT
// <span class="localDateTime" format="mmm dd, yyyy hh:mmTT Z">01/01/2009 12:00:00PM PDT</span>

// SAMPLE OUTOUT
// Jan 01, 2009 05:00AM PDT

// SAMPLE FORMATS
// mmm dd, yyyy hh:mmTT Z     -->     Jan 01, 2009 12:00AM PDT
// mm/dd/yyyy hh:mmTT    -->     01/01/2009 12:00AM
$(function() {

    $(".localDateTime").each(function() {
        var utcDateTime = $(this).text();

        try {
            var format = $(this).attr("format");
            format = (format != undefined && format != "") ? format : "mm/dd/yyyy hh:mmTT";

            var localDateTime = new Date(utcDateTime);

            utcDateTime = localDateTime.format(format);
        }
        catch (e) {
            // alert(utcDateTime);
        }

        $(this).text(utcDateTime);
    });
});


function ContentRotator(sectionName, itemName, itemCount, displayCount, autoPlay) {
    this.contentSection = sectionName;
    this.contentItemName = itemName;
    this.contentItems = (itemCount != null) ? itemCount : 5;                // Total number of content items
    this.contentIndex = 1;
    this.displayItems = (displayCount != null) ? displayCount : 1; 			// Total number of content items to be displayed
    this.hoverPause = 0; 				                                    // Whether to pause on hover
    this.inProgress = 0;
    this.delay = 4000; 					                                    // Delay in milliseconds
    this.autoPlay = (autoPlay != null) ? autoPlay : false;

    this.rotate = function() {
        if (this.hoverPause == 1) {
            var arrRandomNumbers = getUniqueRandomNumbers(1, this.contentItems, this.displayItems);

            $('.rotator').remove();
            $('#' + this.contentSection).append('<div class="rotator"></div>');

            for (var i = 0; i < arrRandomNumbers.length; i++) {
                var item = i + 1;

                $('#' + this.contentItemName + arrRandomNumbers[i]).clone().removeAttr("id").show().appendTo('.rotator');
                $('.rotator').append('<br/>');
            }

            if (this.autoPlay) {
                // Call the rotation function again with the delay interval we defined above
                var self = this;
                setTimeout(function() { self.rotate(); }, this.delay);
            }

            // Rotation continues, set rotationInProgress
            this.inProgress = 1;
        }
        else {
            // Rotation is stopped, reset rotationInProgress
            this.inProgress = 0;
        }
    };

    this.start = function() {
        this.hoverPause = 1;

        // Only call the rotation function when we are not in the middle of a rotation delay
        if (this.inProgress == 0) {
            this.inProgress = 1;

            var self = this;
            //setTimeout(function() { self.rotate(); }, this.delay);
            self.rotate();
        }
    };

    this.stop = function() {
        // Stop rotation by setting the continueRotation flag to zero
        this.hoverPause = 0;
    };
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    
    return ""
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + exdate.toUTCString());
}

// Opens KB search tips
function searchTips() {
    window.open("/search_tips.asp", "tips", "width=735,height=600,scrollbars,resizable")
}
