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, errorMessage) {
    var selected = false;

    $(JId(parentId) + " :checkbox").each(

        function () {
            if (!selected) {
                selected = $(this).attr('checked');
            }
        }
    );

    if (!selected) {
        alert(errorMessage);
    }

    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;
}

/*********************** Advanced Search Validation Methods **************************/
function checkSelectedCriteria_ClientValidation(sender, args) {
    args.IsValid = false;
    $('#divAdvancedSearch input').each(function (idx, item) {
        if (item.type == "text" && item.value.length > 0) {
            args.IsValid = true;
        }
    });
    $('#divAdvancedSearch select').each(function (idx, item) {
        $('option:selected', this).each(function () {
            if (this.value > 0) {
                args.IsValid = true;
            }
        })
    });
}

function checkSelectedCriteriaCommPeople_ClientValidation(sender, args) {
    args.IsValid = false;
    $('#community-ppl-select select').each(function (idx, item) {
        $('option:selected', this).each(function () {
            if (this.value > 0) {
                args.IsValid = true;
            }
        })
    });
}

function checkNameCommPeople_ClientValidation(sender, args) {
    args.IsValid = false;
    var item = $('#' + sender.controltovalidate);
    var x = item.attr("PlaceHolder");
	if (item.val().length > 0 && item.val() != x) {
		args.IsValid = true;
	}
}
function checkName_ClientValidation(sender, args) {
    args.IsValid = true;

    var firstName = args.Value;
    if (!IsWildCardMinimumMatch(firstName)) {
        args.IsValid = false;
    }
}

function IsWildCardMinimumMatch(text) {

    var match = true;
    if (text.indexOf("*") > -1 && text.length < 4) {
        match = false;
    }

    return match;
}
/********************** 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 = findEditor(validator);
    var textMaxlength = editor._rootElement.getAttribute('maxlength');
    var contentMaxLength = editor._rootElement.getAttribute('contentMaxLength');
    var editorText = editor.get_text();
    var editorTextLength = GetTextLength(editorText);

    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 = findEditor(validator);
    args.IsValid = !isEmpty(editor.get_text());
}

function isEmpty(text) {
    var editorTextLength = text.replace(/\s+|\n+|\t+/g, "").length;
    return editorTextLength == 0;
}

function findEditor(validator) {
    var editorID = validator.controltovalidate;
    if (typeof (editorID) == 'undefined')
        editorID = validator.ControlIdToValidate;

    return editor = $find(editorID);
}
/**************************************** Create/Editblog post **********************/

function ToggleNodes() {
    $("a.toggle,span.toggle").click(function (event) {
        if ($(this).parent().hasClass("collapsed")) {
            $("span.toggle").each(function () {
                $(this).parent().attr("class", "archivedate collapsed");
            });
            $(this).parent().attr("class", "archivedate expanded");
            $(this).parent('li.archivedate').parent('ul').parent('li.archivedate').attr("class", "archivedate expanded");
        }
        else {
            $(this).parent().attr("class", "archivedate collapsed");
            event.stopPropagation();
        }
    });
}

/********************** 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;

}

/*Function for getting the length after rplacing new line and tabs and white spaces */
function GetTextLength(text) {
    return text.replace(/\n+|\t+/g, "").replace(/\s+/g, " ").length;
}

/* Validate the Signature max Length */
function maxLengthSignature_ClientValidation(sender, args) {
    var txtline = args.Value;
    var txtValue = JH.Utilities.HtmlEncode(txtline);
    var maxLength = $('#' + sender.controltovalidate).attr("maxLength");
    args.IsValid = txtValue.length <= maxLength;
}
/* initialized Tabs */
function InitializedTabs() {
    // Set up a listener so that when anything with a class of 'tab' 
    // is clicked, this function is run.
    $('.tab').click(function () {
        // Remove the 'active' class from the active tab.
        $('#tabs_container > .tabs > li.active').removeClass('active');

        // Add the 'active' class to the clicked tab.
        $(this).parent().addClass('active');

        // Remove the 'tab_contents_active' class from the visible tab contents.
        $('div.tab_contents_active').removeClass('tab_contents_active');

        // Add the 'tab_contents_active' class to the associated tab contents.
        $(this.rel).addClass('tab_contents_active');

        //Update tab hidden field
        var tabId = $(this).attr("tabId");
        $('#tab').val(tabId);
    });
}

function showHideDefaultPersonalMessage(textareaId, defaultMessage) {
    if ($(JId(textareaId)).val() == defaultMessage) { $(JId(textareaId)).val(''); }
    else if ($(JId(textareaId)).val() == "") { $(JId(textareaId)).val(defaultMessage); }
}

function ShowHideContorls(controlToShow, controlToHide) {
    $(JId(controlToShow)).show();
    $(JId(controlToHide)).hide();
}

/* Telerik Filter for Safari */
function OnClientLoad(editor, args) {
    if ($telerik.isSafari) editor.get_filtersManager().add(new SafariFilter());
}
SafariFilter = function () {
    SafariFilter.initializeBase(this);
    this.set_isDom(false);
    this.set_enabled(true);
    this.set_name("RadEditor filter");
    this.set_description("RadEditor filter for safari to replace div with br at save time");
}
SafariFilter.prototype =
{
    getHtmlContent: function (content) {
        var newContent = content;

        newContent = newContent.replace(/<div>|<div .*?>/gi, "<br />").replace(/<\/div>/gi, "");
        return newContent;
    }
}

function OnClientSubmit(editor, args) {
    if ($telerik.isSafari || $telerik.isChrome) {
        editor.fire("FormatStripper", { value: "WORD" });
        editor.fire("FormatStripper", { value: "CSS" });
    }
}

/* TextBox Counter */
jQuery.fn.showCounter = function (max) {
    this.each(function () {
        var CounterText = $(this).attr("counterText");
        var CounterEmptyText = $(this).attr("emptytext");
        var targetID = $(this).attr("labelID");
        var target = document.getElementById(targetID);
        $(this).bind('propertychange input drop keyup focus change paste', function () {
            var textValue = this.value;
            var remainingCount = max - textValue.length;
            if (textValue.length == 0) {
                var text = CounterEmptyText;
            }
            else {
                var text = CounterText;
            }
            text = text.replace("[charCount]", remainingCount);
            text = text.replace("[MaxLength]", max);
            target.innerHTML = text;
        });
    });
};

$().ready(function () {
    $("[showCounter]").each(function () {
        $(this).showCounter($(this).attr("showCounter"))
    });
    activatePlaceHolder();
});

function GetValue(textBoxId) {
    var textBoxValue = document.getElementById(textBoxId);
    return textBoxValue.value;
}

function openPlanManagerWindow(aDeepLink, command, w, h) {
    openPlanManager(aDeepLink, command, w, h, Control_Domain);
}

function activatePlaceHolder() {
	if(hasPlaceholderSupport() != true) {
		$('input[PlaceHolder]').each(function (index, domEle) {
			var $srcElement = $(domEle);
			var placeHolder = $srcElement.attr("PlaceHolder");
			var value = $srcElement.val();
			if ('' == value) {
				$srcElement.val(placeHolder);
			}
		
			$srcElement.focus(function () {
				var placeHolder = $srcElement.attr("PlaceHolder");
				var value = $srcElement.val();
				if (value == placeHolder)
					$srcElement.val('');
			});

			$srcElement.blur(function (event) {
				var placeHolder = $srcElement.attr("PlaceHolder");
				var value = $srcElement.val();
				if ('' == value)
					$srcElement.val(placeHolder);
			});
		});
	}
}

function hasPlaceholderSupport() {
  var input = document.createElement('input');
  return ('placeholder' in input);
}
/********************** Edit Profile Validation Methods ************************/

function ValidateAll() {
    var isGrpOneValid = Page_ClientValidate("validationGroupFirstAccordion");
    var isGrpTwoValid = Page_ClientValidate("validationGroupSecondAccordion");

    var i;
    for (i = 0; i < Page_Validators.length; i++) {
        ValidatorValidate(Page_Validators[i]);
    }

    for (i = 0; i < Page_ValidationSummaries.length; i++) {
        summary = Page_ValidationSummaries[i];
        if (DisplaySummary(summary.validationGroup)) {
            summary.style.display = "";
            $("#divMainErrMessage").show();
        }
    }

    if (isGrpOneValid && isGrpTwoValid)
        return true;
    else
        return false;
}

function DisplaySummary(valGrp) {
    var rtnVal = false;
    for (i = 0; i < Page_Validators.length; i++) {
        if (Page_Validators[i].validationGroup == valGrp) {
            if (!Page_Validators[i].isvalid) {
                rtnVal = true;
                break;
            }
        }
    }
    return rtnVal;
}

function LoadAccordion() {
    $("#accordion").addClass("ui-accordion ui-widget")
  .find("h3")
    .addClass("ui-accordion-header ui-state-default ui-corner-top")
    .prepend('<span class="ui-icon ui-icon-triangle-1-e"></span>')
    .click(function () {
        $(this)
        .toggleClass("ui-state-default")
        .toggleClass("ui-state-active")
        .toggleClass("ui-accordion-header-active")
        .find("> .ui-icon").toggleClass("ui-icon-triangle-1-e ui-icon-triangle-1-s").end()
        .next().toggleClass("ui-accordion-content-active").slideToggle();
        return false;
    })
    .next()
      .addClass("ui-accordion-content  ui-helper-reset ui-widget-content ui-corner-bottom")
      .hide();
}
