var XML_START_TAG   = "<input>";
var XML_END_TAG     = "</input>";
var PLC_FOOTPRINT = "[FOOTPRINT]";
var PLC_COUNTRY = "[COUNTRY]";
var FOOTPRINT = "";
var COUNTRY = "";
var DEFAULT_IMAGE_PROFILE = PLC_FOOTPRINT + "/Images/" + PLC_COUNTRY + "/SocNet/Profile/default-profile-image50.gif";
var IU_POPUP_NAME = 'wwiu_popup';
var IU_POPUP_WIN; 

//IE doesn't support Javascript Array.indexOf method, so we add one
if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

//Extend String type to support trim
if (!String.prototype.trim)
{
    String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }
}

// This function does two things
//  1. Encode html characters so that the text, which is eventually part of an xml, doesn't break it
//  2. Even after encoding, there are certain characters (&, +), which are used to construct a querystring
//    must be encoded again, so that they don't break ajax request, which is sent as a query string
function EncodeText(text)
{
    text = JH.Utilities.HtmlEncode(text);
    text = encodeURIComponent(text);
	
	return text;
}


//--------------------------------------------------------------
// This is the base class for every class that can be serialized
//--------------------------------------------------------------
function Serializable()
{
    Serializable.prototype = {
    
        Serialize : function(){
        
            throw error("This method is not overridden.");
        }
    }
}
//------------------End of Serializable class -----------------


//----------------- point class -----------------------------
function Point(x, y)
{
    this.X = x;
    this.Y = y;
}

//----------------- end of point class ----------------------



//------------------------------------------------------------
//                  Utility Functions
//------------------------------------------------------------

//To check if the key pressed is "Enter" key
function IsEnterKey(event)
{
    var key;

     if(window.event)
          key = window.event.keyCode;     //IE

     else
          key = event.which;     //firefox
     
     if (key == 13)
        return true;
     else
        return false;
}


//This function is called on every page
function RegisterLocale(footprint, country)
{
    FOOTPRINT = footprint;
    COUNTRY = country;
}

function GetDefaultProfileImage()
{
    var imageUrl = DEFAULT_IMAGE_PROFILE.replace(PLC_FOOTPRINT, FOOTPRINT);
    imageUrl = imageUrl.replace(PLC_COUNTRY, COUNTRY);
    return imageUrl;
}

function JId(Id)
{
    return "#" + Id;
}

function PrepareXmlInput(xmlData)
{
    return XML_START_TAG + xmlData + XML_END_TAG;
}

//gets mouse coordinates with respect to document
//works for IE and FF
//Source: Firefox
function GetCoordinates(e) {
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	// posx and posy contain the mouse position relative to the document
	
	var point = new Point(posx, posy);
	
	return point;
}

//removes spaces from both end
function Trim(msg)
{
    var trimmedMsg = msg.replace(/^\s+|\s+$/g, '') ;
    return trimmedMsg;
}


// Update join link after participation request
function UpdateJoinLinks()
{
    var links = document.getElementsByName("JoinLink");
    var div;
    if(links) {
        for(var i=0;i<links.length;i++){links[i].style.display = 'none';}
        var messageDiv = document.getElementsByName("RequestedMessage");
        if(messageDiv) {
            for(var i=0;i<messageDiv.length;i++)
            {
                div = document.createElement("div");
                div.style.display ='block';
                div.innerHTML="Participation Requested";
                messageDiv[i].appendChild(div);
            }
         }
    }
}


/******************* Cookie Utilities : START ******************/
function readCookie(name) 
{
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') 
            c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) 
                return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function createCookie(name, value, days) 
{
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function eraseCookie(name) 
{
	createCookie(name,"",-1);
}
/******************* Cookie Utilities : END ******************/

function ValidateImageUrl(source, args)
{
     var validate = false;
     var imageId = readCookie("WWIU_TempImageId");
     if(!imageId){imageId = 0;}        
     var chkTermsConditions = document.getElementById(GetCheckBoxID());
     if(imageId == 0){validate=true;}
     else{
        if(chkTermsConditions.checked == true){
              validate=true;}
        }
    args.IsValid = validate;
}

/************** String.Format Utility in JS ********************/
function _StringFormatInline() {
    var txt = this;
    for (var i = 0; i < arguments.length; i++) {
        var exp = new RegExp('\\{' + (i) + '\\}', 'gm');
        txt = txt.replace(exp, arguments[i]);
    }
    return txt;
}

function _StringFormatStatic() {
    for (var i = 1; i < arguments.length; i++) {
        var exp = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        arguments[0] = arguments[0].replace(exp, arguments[i]);
    }
    return arguments[0];
}

if (!String.prototype.format) {
    String.prototype.format = _StringFormatInline;
}

if (!String.format) {
    String.format = _StringFormatStatic;
}
/************** String.Format Utility in JS ********************/

function FireDefaultButton(event, target) {
    if (event.keyCode == 13) {
        var defaultButton;
        if (__nonMSDOMBrowser) {
            defaultButton = document.getElementById(target);
        }
        else {
            defaultButton = document.all[target];
        }
        if (defaultButton && typeof (defaultButton.click) != "undefined") {
            defaultButton.click();
            event.cancelBubble = true;
            if (event.stopPropagation) event.stopPropagation();
            return false;
        }
    }
    return true;
}

function CloseIUPopup()
{
    if(IU_POPUP_WIN != null)
    {
        if (IU_POPUP_WIN.closed == false)
        {
            IU_POPUP_WIN.close();
        }
    }

}

//To check all check boxes contained in a parent control
//parentId = parent control id
//checkAllId = Id of the check all box
function checkAll(parentId, checkAllId)
{
  $(JId(parentId) + " :checkbox").attr('checked', $(JId(checkAllId)).is(':checked'));
}

//Function that checks that atleast one check box has been selected.
function SelectACheckBox(parentId)
{
    var selected = false;
    
    $(JId(parentId) + " :checkbox").each(
        
        function()
        {
            if (!selected)
            {
              selected = $(this).attr('checked');
            }
        }
    );
    
    if (!selected)
    {
        alert("No friends have been selected.");
    }
    
    return selected;
}

//HtmlEncode
function HtmlEncode(str) {
    var encode = $('<div/>').text(str).html();
    encode = encode.replace(/"/g, "&quot;");
    return encode;
}


//Tool tip utilities
function ShowToolTip(tooltipID,object){
    var position = $(object).position();
    $("#"+tooltipID).css('left',position.left + $(object).width()+ 15);
    $("#"+tooltipID).css('top',position.top - $("#"+tooltipID).height());
    $("#"+tooltipID).show();
}

function HideToolTip(tooltipID){
    $("#"+tooltipID).hide();
}


/*********************** Blog Posts Update Validation Group **************************/
function UpdateValidationGroup(validationSummaryID, validationGroup) {
        validationSummary = document.getElementById(validationSummaryID);
        if (validationSummary)
            validationSummary.validationGroup = validationGroup;
    }
    
    
/*********************** Edit Profile Validation Methods **************************/
 function ShowBirthYear(checkboxId) {
        var chkBirthyear = document.getElementById(checkboxId);
        if (chkBirthyear && chkBirthyear.checked == true)
            $('#birthYear').attr('style', 'display: none;');
        else
            $('#birthYear').removeAttr('style');
    }

function maxLength_ClientValidation(sender, args) {
        var txtValue = HtmlEncode(args.Value);
        var maxLength = $('#' + sender.controltovalidate).attr("maxLength");
        args.IsValid = txtValue.length <= maxLength;
    }
    
/********************** Canned Search DoKeyWordSearch Method ************************/
function DoKeyWordSearch(ExtendedFieldName, SearchTerm){
        var encoded = "/Search/Search.aspx?" + ExtendedFieldName + "=" + SearchTerm.replace(" ","+");
        window.location = encoded;
    }
    /**************************************** Create/Editblog post **********************/
    function checkLength(validator, args) {
        var editor = $find(validator.controltovalidate);
        var textMaxlength = editor._rootElement.getAttribute('maxlength');
        var contentMaxLength = editor._rootElement.getAttribute('contentMaxLength');
        var editorText = editor.get_text();
        var editorTextLength = editorText.replace(/\n+|\t+/g, "").replace(/\s+/g, " ").length;
        var editorHtmlLength = editor.get_html(true).replace(/\n+|\t+/g, "").replace(/\s+/g, " ").length;

        var isEmptyText = isEmpty(editorText);
        if (isEmptyText == false) {
            args.IsValid = editorTextLength <= textMaxlength;
            if (args.IsValid == true)
                args.IsValid = editorTextLength <= contentMaxLength;
        }
        else {
            args.IsValid = true;
        }
    }

    function checkEmptyContent(validator, args) {
        var editor = $find(validator.controltovalidate);
        args.IsValid = !isEmpty(editor.get_text());
    }

    function isEmpty(text) {
        var editorTextLength = text.replace(/\s+|\n+|\t+/g, "").length;
        return editorTextLength == 0;
    }

/********************** Show/Hide Mood Method ************************/
function ShowMood(showMood){
       if(showMood == "true"){$("#tbrMood").show()}
       else ($("#tbrMood").hide())
}
/********************** Challenge check in table styling Method ************************/
function StyleTable()
{
    var listItems = $("li[name='checkInList']");
    for(i=0;i<listItems.length;i++)
    {
        if(i % 2 == 0){
            $(listItems[i]).removeClass();
            $(listItems[i]).addClass("nonalt");
        }
        else{
            $(listItems[i]).removeClass();
            $(listItems[i]).addClass("alt")
        }
    }
}

/*Function for Sharing/Bookmarking feature */
 function SBClick(provider, linkUrl, bookmarkUrl, bookmarkTitle)
    {
        linkUrl = String.format(linkUrl, encodeURIComponent(bookmarkUrl), encodeURIComponent(bookmarkTitle));
        window.open(linkUrl, 'ww_share', '');
        return;
        
    }
    

