//Internal Functionality
var Profile =
{
    EditShow: function(id) {//show edit section
        for (var ic = 1; ic <= 4; ic++) {
            if ((id == ic)) {
                $("#divProfile" + id).hide();
                $("#divProfile" + id + "Edit").show();
                Common.ScrollToDivPositionSpecificPosition("divProfile" + id + "Edit");
            }
            else {
                $("#divProfile" + ic).show();
                $("#divProfile" + ic + "Edit").hide();
            }
        }


        //    $("#divProfile" + id).hide();
        //    $("#divProfile" + id + "Edit").show();
    },

    EditHide: function(id) {//edit edit section
        $("#divProfile" + id).show();
        $("#divProfile" + id + "Edit").hide();
        Common.ScrollToDivPositionSpecificPosition("divProfile" + id);
    },

    HideViewAll: function(id) {//hide public section view all link
    $("#spViewAll" + id).hide();
    },

    ShowDetails: function(DivToScrollID, OnlineStatusDivID) {//edit edit section
        LoginStatus.HideStatusDiv(OnlineStatusDivID);
        Common.ScrollToDivPosition(DivToScrollID);
        Common.InitilizeAllComponents();
    },

    Visitor:
    {
        GetListingSucceed: function(ScrollDivID) {
            Common.ScrollToDivPosition(ScrollDivID);
            Common.InitilizeAllComponents();
        }
    },

    BasicInfo:
    {
        ValidateEditMode: function(USAID, FormID) {
            $("#" + FormID).validate({
                rules: {
                    StateSelected: {
                        required: function() {
                            if ($("#CountrySelected").val() == USAID) {
                                return true;
                            }
                            else {
                                return false;
                            }
                        }
                    },
                    State: {
                        required: function() {
                            if ($("#CountrySelected").val() != USAID) {
                                return true;
                            }
                            else {
                                return false;
                            }
                        }
                    },
                    City: {
                        required: true
                    },
                    ZipCode: {
                        required: true
                    }
                },
                messages: {
                    StateSelected: {
                        required: "You must select state."
                    },
                    State: {
                        required: "You must enter state."
                    },
                    City: {
                        required: "You must enter city."
                    },
                    ZipCode: {
                        required: "You must enter zip."
                    }
                }
            });

            if ($("#" + FormID).valid()) {
                return true;
            }
            else {
                return false;
            }
        },

        Validate: function(USAID, FormID) {
            $("#" + FormID).validate({
                rules: {
                    StateID: {
                        required: function() {
                            if ($("#CountryID").val() == USAID) {
                                return true;
                            }
                            else {
                                return false;
                            }
                        }
                    },
                    State: {
                        required: function() {
                            if ($("#CountryID").val() != USAID) {
                                return true;
                            }
                            else {
                                return false;
                            }
                        }
                    },
                    City: {
                        required: true
                    },
                    ZipCode: {
                        required: true
                    }
                },
                messages: {
                    StateID: {
                        required: "You must select state."
                    },
                    State: {
                        required: "You must enter state."
                    },
                    City: {
                        required: "You must enter city."
                    },
                    ZipCode: {
                        required: "You must enter zip."
                    }
                }
            });

            if ($("#" + FormID).valid()) {
                return true;
            }
            else {
                return false;
            }
        }
    },

    PerfectMatch:
    {
        ValidateEditMode: function() {
            var Valid = true;

            // Checking Height

            if (document.getElementById('FuturePartnerHeightFeetFromID').selectedIndex > document.getElementById('FuturePartnerHeightFeetToID').selectedIndex) {
                $("#lblFromHeightGreaterMsg").show();
                $("#FuturePartnerHeightFeetFromID").focus();

                Valid = false;
            }
            else if (document.getElementById('FuturePartnerHeightFeetFromID').selectedIndex == document.getElementById('FuturePartnerHeightFeetToID').selectedIndex) {
                if (document.getElementById('FuturePartnerHeightInchesFromID').selectedIndex > 1 && document.getElementById('FuturePartnerHeightInchesFromID').selectedIndex > document.getElementById('FuturePartnerHeightInchesToID').selectedIndex) {
                    $("#lblFromHeightGreaterMsg").show();
                    $("#FuturePartnerHeightFeetFromID").focus();

                    Valid = false;
                }
            }
            else { $("#lblFromHeightGreaterMsg").hide(); }

            // Checking Age
            if ($("#FuturePartnerAgeFromID").val() > $("#FuturePartnerAgeToID").val()) {
                $("#lblFromAgeGreaterMsg").show();
                $("#FuturePartnerAgeFromID").focus();

                Valid = false;
            }
            else {
                $("#lblFromAgeGreaterMsg").hide();
            }

            return Valid;
        },

        Validate: function() {
            var Valid = true;

            // Checking Height
            if (document.getElementById('HeightFeetFromID').selectedIndex > document.getElementById('HeightFeetToID').selectedIndex) {
                $("#lblFromHeightGreaterMsg").show();
                $("#HeightFeetFromID").focus();

                Valid = false;
            }
            else if (document.getElementById('HeightFeetFromID').selectedIndex == document.getElementById('HeightFeetToID').selectedIndex) {
                if (document.getElementById('HeightInchesFromID').selectedIndex > 1 && document.getElementById('HeightInchesFromID').selectedIndex > document.getElementById('HeightInchesToID').selectedIndex) {
                    $("#lblFromHeightGreaterMsg").show();
                    $("#HeightFeetFromID").focus();

                    Valid = false;
                }
            }
            else { $("#lblFromHeightGreaterMsg").hide(); }

            // Checking Age
            if ($("#AgeFromID").val() > $("#AgeToID").val()) {
                $("#lblFromAgeGreaterMsg").show();
                $("#AgeFromID").focus();

                Valid = false;
            }
            else {
                $("#lblFromAgeGreaterMsg").hide();
            }

            return Valid;
        }
    },

    Education:
    {
        MaxUniCollection: 5,
        MaxSchoolCollection: 5,
        CurUniCollection: 0,
        CurSchoolCollection: 0,
        DomIndex: 21, //DomIndex has to be greater than the total of MaxUniCollection + MaxSchoolCollection

        AddMoreUni: function() {
            if (Profile.Education.CurUniCollection < Profile.Education.MaxUniCollection) {
                Profile.Education.CurUniCollection++;
                Profile.Education.DomIndex++;
                $("#divUniversityCollection").append('<div id=\"divUniVar' + Profile.Education.DomIndex + '\" class=\"adduniv\"></div>');
                $("#divUniVar" + Profile.Education.DomIndex).html($('#divTempUni').html());
                $("#divUniVar" + Profile.Education.DomIndex + " > .fields_510 > .inputbox311 > .removeUni").html('<a class=\"blue_lnk\" href=\"javascript:\" onclick=\"javascript:Profile.Education.RemoveUni(\'divUniVar' + Profile.Education.DomIndex + '\');\">Remove College / University</a>');

                if (Profile.Education.CurUniCollection > 0) {
                    $("#divNoUni").hide();
                    $("#divUniAddMore").show();
                }

                if (Profile.Education.CurUniCollection == Profile.Education.MaxUniCollection) {
                    $("#divUniAddMore").hide();
                }
            }
        },

        RemoveUni: function(DivID) {
            Profile.Education.CurUniCollection--;
            $("#" + DivID).remove();
            if (Profile.Education.CurUniCollection < Profile.Education.MaxUniCollection) {
                $("#divUniAddMore").show();
            }

            if (Profile.Education.CurUniCollection == 0) {
                $("#divNoUni").show();
                $("#divUniAddMore").hide();
            }
        },

        AddMoreSchool: function() {
            if (Profile.Education.CurSchoolCollection < Profile.Education.MaxSchoolCollection) {
                Profile.Education.CurSchoolCollection++;
                Profile.Education.DomIndex++;
                $("#divSchoolCollection").append('<div id=\"divSchoolVar' + Profile.Education.DomIndex + '\" class=\"addschool\"></div>');
                $("#divSchoolVar" + Profile.Education.DomIndex).html($('#divTempSchool').html());
                $("#divSchoolVar" + Profile.Education.DomIndex + " > .fields_510 > .inputbox311 > .removeUni").append('<a class=\"blue_lnk\" href=\"javascript:\" onclick=\"javascript:Profile.Education.RemoveSchool(\'divSchoolVar' + Profile.Education.DomIndex + '\');\">Remove School</a>');

                if (Profile.Education.CurSchoolCollection > 0) {
                    $("#divNoSchool").hide();
                    $("#divSchoolAddMore").show();
                }
                if (Profile.Education.CurSchoolCollection == Profile.Education.MaxSchoolCollection) {
                    $("#divSchoolAddMore").hide();
                }
            }
        },

        RemoveSchool: function(DivID) {
            Profile.Education.CurSchoolCollection--;
            $("#" + DivID).remove();
            if (Profile.Education.CurSchoolCollection < Profile.Education.MaxSchoolCollection) {
                $("#divSchoolAddMore").show();
            }

            if (Profile.Education.CurSchoolCollection == 0) {
                $("#divNoSchool").show();
                $("#divSchoolAddMore").hide();
            }
        },

        SetValuesForEdit: function(SchoolCount, UniversityCount) {
            Profile.Education.CurSchoolCollection = $(".addschool").length;
            Profile.Education.CurUniCollection = $(".adduniv").length;
        }
    }
}

var Album =
{
  ValidateCreate: function(FormID) {
    $("#" + FormID).validate({
      rules: {
        Name: {
          required: true
        },
        WhoCanSee: {
          required: true
        }
      },
      messages: {
        Name: {
          required: "You must enter name."
        },
        WhoCanSee: {
          required: "You must select privacy."
        }
      }
    });

    if ($("#" + FormID).valid()) {
      return true;
    }
    else {
      return false;
    }
  },

  CreateSucceed: function(hdnID) {
    if ($("#" + hdnID).length) {
      SWFAddress.setValue($("#" + hdnID).val());
    }
  }
}

var AlbumFile =
{
  Organize:
    {
      InitializeSortable: function(ScrollDivID) {
        $("#sortable").sortable();
        $("#sortable").disableSelection();
        Common.ScrollToDivPosition(ScrollDivID);
        Common.InitilizeAllComponents();
      },

      CheckCurrentOrder: function() {
        $('#hdnAlbumFilesSortOrder').val("");
        $("#sortable").children("li").each(
	            function() {
	              var cVal = $('#hdnAlbumFilesSortOrder').val();
	              $('#hdnAlbumFilesSortOrder').val(cVal + ',' + $(this).attr("itemid"));
	            }
	        )
      }
    },

  Description:
    {
      ShowInEditMode: function() {
        if ($(".desc_edit").css('display') == "none") {
          $(".desc_edit").slideDown("normal");
          $("#editDescription").slideUp("normal");
        }
      },

      ShowInEditCloseMode: function() {
        if ($(".desc_edit").css('display') == "block") {
          $(".desc_edit").slideUp("normal");
          $("#editDescription").slideDown("normal");
        }
      },

      ShowInAddMode: function() {
        if ($(".desc_edit").css('display') == "none") {
          $(".desc_edit").slideDown("normal");
          $("#addDescription").slideUp("normal");
        }
      },

      ShowInAddCloseMode: function() {
        if ($(".desc_edit").css('display') == "block") {
          $(".desc_edit").slideUp("normal");
          $("#addDescription").slideDown("normal");
        }
      },

      CheckLength: function() {
        if ($.trim($('#AlbumDescription').val()) != "") {
          return true;
        }
        else
          return false;
      }
    },

  Rating:
    {
      GetRating: function() {
        $(function() {
          $('.auto-submit-star').rating({
            callback: function(value, link) {
              $("#btnSubmitRating").click();
            }
          });
        });
      },

      AppendMouseOverMethods: function(RatingDivID) {
        $('#' + RatingDivID).mouseover(function() { $('#ratings').hide(); $('#Status').show(); });
        $('#' + RatingDivID).mouseout(function() { $('#Status').hide(); $('#ratings').show(); });
      },

      Succeed: function(RatingDivID) {
        this.BindData(RatingDivID);
        document.getElementById('ratings').innerHTML = '<b>Thanks for rating!</b>';
        document.getElementById('Status').innerHTML = '<b>Thanks for rating!</b>';
      },

      BindData: function(RatingDivID) {
        this.GetRating();
        this.AppendMouseOverMethods(RatingDivID);
      }
    }
}

var Comment =
{
  Validate: function(FormID) {
    $("#" + FormID).validate({
      rules: {
        CommentDescription: {
          required: true,
          maxlength: 1000
        }

      },
      messages: {
        CommentDescription: {
          required: "You must specify comment.",
          maxlength: "Comment must be less than 1000 Characters."
        }
      }
    });

    if ($("#" + FormID).valid()) {
      return true;
    }
    else {
      return false;
    }
  },

  CheckLength: function() {
    if ($.trim($('#CommentDescription').val()) != "") {
      return true;
    }
    else
      return false;
  },

  PostCommentBegin: function() {
    $('#CommentDescription').attr('readonly', 'readonly');
    $('#btnSubmitComment').attr('disabled', 'disabled');
  },

  DeleteCommentSucceed: function(DivID) {
    $('#' + DivID).animate({ opacity: 'hide' }, 'slow');
  }
}

var Common =
{
  FadeOutTime: 2000,
  HasScrolled: false,

  FadeOut: function(fn) {
    setTimeout(fn, Common.FadeOutTime);
  },

  FadeOutWithTime: function(fn, time) {
    setTimeout(fn, time);
  },

  AjaxRequestComplete: function(content, IsLoginContent, LoginUrl) {
    if (content.get_data() == IsLoginContent) {
      document.location.href = LoginUrl;
    }
  },

  AjaxRequestFailure: function(content, RedirectUrl) {
    //jAlert(content.get_data());
    jAlert('There is an  error. Please bear with us.');
    document.location.href = RedirectUrl;
  },

  CheckTextAreaLength: function(TextBoxID) {
    if ($.trim($('#' + TextBoxID).val()) != "") {
      return true;
    }
    else
      return false;
  },

  

  ScrollToDivPosition: function(DivID) {
  if (!Common.HasScrolled) {
      var divTop = $('#' + DivID).offset().top;
      //$.scrollTo(divTop, 0, { duration: 1000 });
      //window.scroll(0, divTop);
      $.scrollTo(0, 0, { duration: 0 });

    }
    Common.HasScrolled = false;
  },

  ScrollToDivPositionSpecificPosition: function(DivID) {
    var divTop = $('#' + DivID).offset().top;
    //$.scrollTo(divTop, 0, { duration: 1000 });
    window.scroll(0, divTop);
    Common.HasScrolled = true;
    //$.scrollTo(0, 0, { duration: 0 });
  },

  ShowStatesDropdown: function(USAID, ID, DLL, TXT) {
    if ($('#' + ID).val() == USAID) {
      $('#' + DLL).show();
      $('#' + TXT).hide();
    }
    else {
      $('#' + DLL).hide();
      $('#' + TXT).show();
    }
  },

  ValidateMaxLength: function(txtbox, length) {
    if (txtbox.value.length > length) {
      txtbox.value = txtbox.value.substring(0, length);
    }
  },

  EmptyTextBox: function(ID) {
    $('#' + ID).val('');
  },

  /// Simple Hide Function for any class
  ToggleDivVisibility: function(ID) {
    $("#" + ID).slideToggle("normal");
  },

  ToggleCheckBoxes: function() {
    var $checkboxes = $('input[type=checkbox][class=list_input_chk]');
    if (!($checkboxes).attr('checked')) {
      $checkboxes.attr('checked', 'checked');
      return false;
    }
    else {
      $checkboxes.removeAttr('checked');
      return false;
    }
  },

  gotFocus: function(ctl, val) {
    if ($('#' + ctl.id).val() == val) {
      $('#' + ctl.id).val('');
      $('#' + ctl.id).removeClass("search_input_lostFocus");
      $('#' + ctl.id).addClass("search_input_gotFocus");
    }
  },

  lostFocus: function(ctl, val) {
    if ($('#' + ctl.id).val() == '') {
      $('#' + ctl.id).val(val);
      $('#' + ctl.id).removeClass("search_input_gotFocus");
      $('#' + ctl.id).addClass("search_input_lostFocus");

    }
  },

  IsCheckBoxChecked: function() {
    var $checkboxes = $('input[type=checkbox][class=list_input_chk]');
    for (var i = 0; i < $checkboxes.length; i++) {
      if ($checkboxes[i].checked == true) {
        return true;
      }
    }
    return false;
  },

  HideDivWithOpacityEffects: function(DivID) {
    $('#' + DivID).animate({ opacity: 'hide' }, 'slow');
  },

  ShowDivWithOpacityEffects: function(DivID) {
    $('#' + DivID).animate({ opacity: 'show' }, 'slow');
  },

  moreDo: function(DivToShowId, DivToHideId) {
    $("#" + DivToShowId).show();
    $("#" + DivToHideId).hide();
  },

  moreDoNew: function(DivToShowId, DivToHideId) {
    $("#" + DivToShowId).show();
    $("#" + DivToHideId).hide();
  },
  RefreshCaptcha: function(URL, ImageID) {
    var now = new Date();
    $('#' + ImageID).attr("src", URL + "?" + now.getTime());
  },

  ValidateNoPreference: function(ListBox) {
    if (ListBox.options.length > 1) {
      if (ListBox.selectedIndex > 0) {
        ListBox.options[0].selected = false;
      }
      else if (ListBox.selectedIndex == 0) {
        for (var i = 1; i < ListBox.options.length; i++) {
          if (ListBox.options[i].selected) {
            ListBox.options[i].selected = false;
          }
        }
      }
    }
  },

  CopyToClip: function(MoviePath, ProfileURL, SpanID, ClipboardUrl, hashUrl, ProfUrl) {

    //Create a new clipboard client
    ZeroClipboard.moviePath = MoviePath;
    var clip = new ZeroClipboard.Client();

    //Glue the clipboard client to the last td in each row
    clip.glue($('#' + SpanID)[0]);
    clip.setText(ProfileURL);

    //Add a complete event to let the user know the text was copied
    clip.addEventListener('complete', function(client, text, HashURL) {
      tb_show(null, ClipboardUrl + "&ProfUrl=" + ProfUrl + "&hashUrl=" + hashUrl, false)
      //jAlert("Copied text to clipboard:\n" + text);
    });
  },

  ReplaceAll: function(stringText, stringToFind, stringToReplace) {
    var temp = stringText;
    var index = temp.indexOf(stringToFind);
    while (index != -1) {
      temp = temp.replace(stringToFind, stringToReplace);
      index = temp.indexOf(stringToFind);
    }
    return temp;
  },

  TriggerClick: function(ID) {
    $('#' + ID).trigger('click');
  },

  InitilizeAllComponents: function() {
    InitilizeThickboxAjax();
  }
}

var LoginStatus =
{
  SendRequest: function(PostURL) {
    $.ajax({
      type: "POST",
      url: PostURL,
      data: "{}",
      contentType: "application/json; charset=utf-8",
      dataType: "json"
    });
  },

  Update: function(PostURL) {
    //60000 Miliseconds = 1 min
    LoginStatus.SendRequest(PostURL);
    setInterval(function() { LoginStatus.SendRequest(PostURL); }, 60000);
  },

  HideStatusDiv: function(DivID, Effect) {
    if (Effect == '')
      $("#" + DivID).hide();
    else
      $("#" + DivID).hide(Effect);
  },

  StatusMessageLength: function(MessageTextBoxID) {
    if ($.trim($('#' + MessageTextBoxID).val()) != "") {
      return true;
    }
    else
      return false;
  }
}

var AjaxURLHandling =
{
  DoHit: true,

  SetCustomURL: function(StaticPreID) {
    if (AjaxURLHandling.DoHit) {
      if (SWFAddress.getValue().length > 1) {
        var linkID = StaticPreID;
        var ParentlinkID = StaticPreID;

        linkID = linkID + Common.ReplaceAll(SWFAddress.getValue(), "/", "-");
        if (SWFAddress.getPathNames().length > 0)
          ParentlinkID = ParentlinkID + '-' + SWFAddress.getPathNames()[0];

        //javascript: $('#lnkAjax-my-profile').trigger('click');
        try {
          if ($('#' + linkID).length) {
            $('#' + linkID).trigger('click');
          }
          else {
            $('#' + ParentlinkID).trigger('click');
          }
        }
        catch (e) {
          window.onload = function() {
            if ($('#' + linkID).length) {
              $('#' + linkID).trigger('click');
            }
            else {
              $('#' + ParentlinkID).trigger('click');
            }
          };
        }
      }
    }

    AjaxURLHandling.DoHit = true;
    //if (SWFAddress.getPathNames().length > 0)
    //SWFAddress.setTitle(Common.ReplaceAll(SWFAddress.getPathNames()[0], "-", " "));
  },

  SetHashURL: function(hashURL) {
    AjaxURLHandling.DoHit = false;
    SWFAddress.setValue(hashURL);
    AjaxURLHandling.DoHit = true;
  },

  GetDataForURL: function(DefaultUrlToHit, PreURL, UpdatePanelDivID, CheckSession, LoginUrl, ScrollToDivID, DoScroll) {
    if (SWFAddress.getValue().length > 1) {
      PreURL += SWFAddress.getValue();
      HandleAjaxRequest.SendPostRequest(PreURL, UpdatePanelDivID, CheckSession, LoginUrl, ScrollToDivID, DoScroll);
    }
    else {
      HandleAjaxRequest.SendPostRequest(DefaultUrlToHit, UpdatePanelDivID, CheckSession, LoginUrl, ScrollToDivID, DoScroll);
    }
  }
}

var HandleAjaxRequest =
{
  SectionNavLt: 0,
  SectionNavRt: 0,

  SendPostRequest: function(PostURL, UpdatePanelDivID, CheckSession, LoginUrl, ScrollToDivID, DoScroll) {
    $.ajax({
      type: "POST",
      url: PostURL,
      data: "{}",
      beforeSend: function(event, request) {
        //handel complete here
        //jAlert("send");
      },
      complete: function(event, request, settings) {
        //handel complete here
      },
      success: function(html) {
        if (html == CheckSession) {
          document.location.href = LoginUrl;
        }
        else {
          if (DoScroll) {
            //$('#' + UpdatePanelDivID).hide();
            $('#' + UpdatePanelDivID).html(html);
            //$('#' + UpdatePanelDivID).show('slow');
            Common.ScrollToDivPosition(ScrollToDivID);
          }
          else {
            $('#' + UpdatePanelDivID).html(html);
          }
        }
        Common.InitilizeAllComponents();
      },
      error: function(request, error) {
        //handel error here
        //jAlert("readyState: " + request.readyState + "\nstatus: " + request.status);
        //jAlert("responseText: " + request.responseText);
      }
    });
  },

  SendNavPostRequest: function(PostURL, UpdatePanelDivID, CheckSession, LoginUrl, CurrentSection, IsRightNavigation) {
    // Hit Only When section is different :-)
    if (HandleAjaxRequest.SectionNavLt == CurrentSection && !IsRightNavigation) {
      return;
    }
    else if (!IsRightNavigation) {
      HandleAjaxRequest.SectionNavLt = CurrentSection;
    }

    if (HandleAjaxRequest.SectionNavRt == CurrentSection && IsRightNavigation) {
      return;
    }
    else if (IsRightNavigation) {
      HandleAjaxRequest.SectionNavRt = CurrentSection;
    }

    $.ajax({
      type: "POST",
      url: PostURL,
      data: "{}",
      beforeSend: function(event, request) {
        //handel complete here
        //jAlert("send");
      },
      complete: function(event, request, settings) {
        //handel complete here
      },
      success: function(html) {
        if (html == CheckSession) {
          document.location.href = LoginUrl;
        }
        else {
          $('#' + UpdatePanelDivID).html(html);
        }

        Common.InitilizeAllComponents();
      },
      error: function(request, error) {
        //handel error here
        //jAlert("readyState: " + request.readyState + "\nstatus: " + request.status);
        //jAlert("responseText: " + request.responseText);
      }
    });
  },

  SendPostRequestPublic: function(PostURL, UpdatePanelDivID, ScrollToDivID, DoScroll) {
    $.ajax({
      type: "POST",
      url: PostURL,
      data: "{}",
      beforeSend: function(event, request) {
        //handel complete here
        //jAlert("send");
      },
      complete: function(event, request, settings) {
        //handel complete here
      },
      success: function(html) {
        if (DoScroll) {
          //$('#' + UpdatePanelDivID).hide();
          $('#' + UpdatePanelDivID).html(html);
          //$('#' + UpdatePanelDivID).show('slow');
          //Common.ScrollToDivPosition(ScrollToDivID);
        }
        else {
          $('#' + UpdatePanelDivID).html(html);
        }
        Common.InitilizeAllComponents();
      },
      error: function(request, error) {
        //handel error here
        //jAlert("readyState: " + request.readyState + "\nstatus: " + request.status);
        //jAlert("responseText: " + request.responseText);
      }
    });
  },

  SendNavPostRequestPublic: function(PostURL, UpdatePanelDivID, CurrentSection, IsRightNavigation) {
    // Hit Only When section is different :-)
    if (HandleAjaxRequest.SectionNavLt == CurrentSection && !IsRightNavigation) {
      return;
    }
    else if (!IsRightNavigation) {
      HandleAjaxRequest.SectionNavLt = CurrentSection;
    }

    if (HandleAjaxRequest.SectionNavRt == CurrentSection && IsRightNavigation) {
      return;
    }
    else if (IsRightNavigation) {
      HandleAjaxRequest.SectionNavRt = CurrentSection;
    }

    $.ajax({
      type: "POST",
      url: PostURL,
      data: "{}",
      beforeSend: function(event, request) {
        //handel complete here
        //jAlert("send");
      },
      complete: function(event, request, settings) {
        //handel complete here
      },
      success: function(html) {
        $('#' + UpdatePanelDivID).html(html);
        Common.InitilizeAllComponents();
      },
      error: function(request, error) {
        //handel error here
        //jAlert("readyState: " + request.readyState + "\nstatus: " + request.status);
        //jAlert("responseText: " + request.responseText);
      }
    });
  },

  SetHtml: function(DivMain, DivMainRt, IsWideView) {
    $("#" + DivMain).attr('class', '');
    $("#" + DivMainRt).attr('class', '');

    if (IsWideView) {
      $("#" + DivMain).addClass('mid_section_wide');
      $('#' + DivMainRt).html('');
      $('#' + DivMainRt).hide();
    }
    else {
      $("#" + DivMain).addClass('mid_section');
      $("#" + DivMainRt).addClass('right_section_pv');
    }
  }
}

var Folder =
{
  CheckNameLength: function(FolderTextBoxID) {
    if ($.trim($('#' + FolderTextBoxID).val()) != "") {
      return true;
    }
    else
      return false;
  },

  BindContacts: function(DivID) {
    Common.ScrollToDivPosition(DivID);
    Common.InitilizeAllComponents();
  },

  BindMessages: function(DivID) {
    Common.ScrollToDivPosition(DivID);
    Common.InitilizeAllComponents();
  },

  MoveToSucceed: function(ID) {
    $('#' + ID).trigger('click');
    Common.InitilizeAllComponents();
  },

  EditSucceed: function(BtnID) {
    if ($('#hdnFolderOldID').val() == $('#hdnFolderNewID').val() && $('#hdnFolderOldName').val() != $('#hdnFolderNewName').val()) {
      Folder.MoveToSucceed(BtnID);
      SWFAddress.setValue($('#hdnFolderNewHashLink').val());
      Common.InitilizeAllComponents();
    }
  },

  DeleteSucceed: function(BtnID, HashURL) {
    Folder.MoveToSucceed(BtnID);
    SWFAddress.setValue(HashURL);
    Common.InitilizeAllComponents();
  },

  DeleteSentMessages: function(ID) {
    $('#' + ID).trigger('click');
  },

  MoveConnection: function(obj, hdnID, hdnVal, btnID) {
    if (obj.selectedIndex != 0) {
      if (Common.IsCheckBoxChecked()) {
        $('#' + hdnID).val(hdnVal);
        $('#' + btnID).trigger('click');
      }
      else {
        jAlert("Please select atleast one connection to move.");
        obj.selectedIndex = 0;
      }
    }
  },

  DeleteConnection: function(hdnID, hdnVal, btnID) {
    if (Common.IsCheckBoxChecked()) {
      $('#' + hdnID).val(hdnVal);
      $('#' + btnID).trigger('click');
    }
    else {
      jAlert("Please select atleast one connection to delete.");
    }
  },

  BindOptionsDDL: function(SelecedIndex) {
    if (SelecedIndex > 0) {
      $('#divSelectedOption').html($('#divSelOptions' + SelecedIndex.toString()).html());
      $('#divSelectedOption').show();
    }
    else {
      $('#divSelectedOption').html('');
      $('#divSelectedOption').hide();
    }
  },

  BrowseConnection: function(obj, hdnID, hdnVal, btnID) {
    if (obj.selectedIndex != 0) {
      $('#' + hdnID).val(hdnVal);
      $('#' + btnID).trigger('click');
    }
  },

  SearchAllConnections: function(SearchBoxID, SeacrhDefaultValue, URLToHit) {
    if ($('#' + SearchBoxID).val().trim() != SeacrhDefaultValue && $('#' + SearchBoxID).val().trim() != '') {
      SWFAddress.setValue(URLToHit + $('#' + SearchBoxID).val());
    }
  },

  CreateSucceed: function(SiteURL, UpdatePanelDivID, CheckSession, LoginUrl, BtnID) {
    if (SWFAddress.getValue().trim() != '') {
      SiteURL += SWFAddress.getValue().trim();
      HandleAjaxRequest.SendPostRequest(SiteURL, UpdatePanelDivID, CheckSession, LoginUrl, '', false);
      Folder.MoveToSucceed(BtnID);
    }

    Common.InitilizeAllComponents();
  },

  GetFormerSchoolFriends: function(URL) {
    URL += "?PersonName=" + $('#txtFormerPersonName').val().trim() + "&SchoolUniversityName=" + $('#txtFormerSchoolUniversityName').val().trim() + "&SchoolUniversityYear=" + $('#ddlFormerSchoolUniversityYear').val().trim();
    SWFAddress.setValue(URL);
    return false;
  },

  InviteMoreFriends: function() {
    $('#InvitationTo').val('');
    $('#InvitationMessage').val('');
    $('div.InviteFriendsForm').show();
    $('div.InviteFriendsList').hide();
  },

  ValidateCreate: function(FormID) {
    $.validator.addMethod(
            "regexName",
            function(value, element) {
              var re = new RegExp('^[a-zA-Z0-9\\ ]*$');
              return this.optional(element) || re.test(value);
            },
            "Folder name only accepts [a-z, A-Z, 0-9 or space]."
        );

    $("#" + FormID).validate({
      rules: {
        Name: {
          required: true,
          regexName: true
        }
      },
      messages: {
        Name: {
          required: "You must enter name."
        }
      }
    });

    if ($("#" + FormID).valid()) {
      return true;
    }
    else {
      return false;
    }
  }
}


var Update =
{
  ValidatePostStatus: function(inputId) {
    if ($('#' + inputId).val() == "" || $('#' + inputId).val() == "What\'s happening in your world ...")
      return false;
    else
      return true;
  },

  ValidateStatusComment: function(inputId) {
    if ($('#' + inputId).val() == "" || $('#' + inputId).val().toLowerCase() == "write a comment ...")
      return false;
    else
      return true;
  },

  Hide: function(DivHideId, DivShowId) {
    $('#' + DivHideId).hide();
    $('#' + DivShowId).show();
  },

  Remove: function(DivHideId, DivShowId, DivConnectionActivity, DivNoConnectionEventListing) {
    $('#' + DivHideId).remove();
    $("div[" + DivShowId + "]").each(function() {
      if ($('#' + this.id.replace('Event', 'Hide')).css("display") == "block")
        $('#' + this.id.replace('Event', 'Hide')).remove();
      $('#' + this.id).remove();
    });

    if ($("#" + DivConnectionActivity).children("div").children("div[member]").size() == 0) {
      $("#" + DivNoConnectionEventListing).show();
    }
  },

  RemoveHideContact: function(divId) {
    $('#div_' + divId).remove();
  },

  PostHideConnections: function(DivID, HiddenID) {
    $('#' + HiddenID).val('');
    $("#" + DivID).children("div").each(function() {
      $('#' + HiddenID).val($('#' + HiddenID).val() + this.id.replace('div_', '') + ",");
    });
  },

  ContactOlderPostSucceed: function(OlderPostDivId, DivConnectionActivity, DivNoConnectionEventListing) {
    $('#' + OlderPostDivId).remove();
    if ($("#" + DivConnectionActivity).children("div").children("div[member]").size() > 0 && $('#' + DivNoConnectionEventListing).css("display") == "block") {
      $('#' + DivNoConnectionEventListing).hide();
    }
    Common.InitilizeAllComponents();
  },

  PersonalOlderPostSucceed: function(OlderPostDivId, DivPersonalEventListing, DivNoPersonalEventListing) {
    $('#' + OlderPostDivId).remove();
    if ($("#" + DivPersonalEventListing).children("div[member]").size() > 0 && $('#' + DivNoPersonalEventListing).css("display") == "block") {
      $('#' + DivNoPersonalEventListing).hide();
    }
    Common.InitilizeAllComponents();
  },

  ShowPersonalActivityEmptyBox: function(DivMyPost, DivPersonalEventListing, DivNoPersonalEventListing) {
    if (($("#" + DivPersonalEventListing).children("div[member]").size() + $("#" + DivPersonalEventListing).children("#" + DivMyPost).children("div[member]").size()) == 0) {
      $('#' + DivNoPersonalEventListing).show();
    }
  },

  RemoveDiv: function(divId) {
    $('#' + divId).remove();
  },

  OlderPostBegin: function(OlderPostAId) {
    $('#' + OlderPostAId).attr('disabled', 'disabled');
  },

  HidePersonalActivityEmptyBox: function(content, DivID, TextBoxID, spanLatestStatusID, Message) {
    $('#' + DivID).hide();
    // Creating dom of result
    //$("#" + spanLatestStatusID).html($(content.get_data()).children("div:first").children("div:last").children("span:last").html());
    $("#" + spanLatestStatusID).html($("#" + TextBoxID).val());
    $("#" + TextBoxID).val(Message);
    Common.InitilizeAllComponents();
  },

  PostAlbumCommentSucceed: function(ID, Val) {
    $("#" + ID).val(Val);
    Common.InitilizeAllComponents();
  },

  PostStatusCommentSucceed: function(ID, Val) {
    $("#" + ID).val(Val);
    Common.InitilizeAllComponents();
  },

  DeleteAlbumCommentSucceed: function(DivID) {
    $('#' + DivID).animate({ opacity: 'hide' }, 'slow');
    tb_remove();
  },

  DeleteStatusCommentSucceed: function(DivID) {
    $('#' + DivID).animate({ opacity: 'hide' }, 'slow');
    tb_remove();
  },

  EditUpdatesSucceed: function(FormID, RefreshURL) {
    document.forms[FormID].action = RefreshURL;
    document.forms[FormID].method = 'POST';
    document.forms[FormID].submit();
  },

  HideDelete: function(DivID) {
    $("#" + DivID).hide();
  },

  ShowDelete: function(DivID) {
    $("#" + DivID).show();
  },

  ViewAllCommentSucceed: function(aObject) {
    $(aObject).remove();
    Common.InitilizeAllComponents();
  }
}


var FileUploader =
{
  ajaxFileUpload: function(FileUploaderData) {
    $("#" + FileUploaderData.UploadingImage)
		.ajaxStart(function() {
		  $(this).show();
		})
		.ajaxComplete(function() {
		  $(this).hide();
		});

    $.ajaxFileUpload
		(
			{
			  url: FileUploaderData.UploadingUrl,
			  secureuri: false,
			  fileElementId: FileUploaderData.fileToUpload,
			  dataType: 'json',
			  beforeSend: function() {
			    $("#" + FileUploaderData.UploadingImage).show();
			  },
			  complete: function(data, status) {
			    $("#" + FileUploaderData.UploadingImage).hide();
			  },
			  success: function(data, status) {
			    FileUploaderData.OnComplete(data);
			  }
			}
		)
    return false;
  }
}


var Message =
{
  ValidateReply: function(FormID) {
    $("#" + FormID).validate({
      rules: {
        Subject: {
          required: true
        },
        Body: {
          required: true
        }
      },
      messages: {
        Subject: {
          required: "You must enter subject."
        },
        Body: {
          required: "You must enter message."
        }
      }
    });

    if ($("#" + FormID).valid()) {
      $("#" + ReplyMessageControl.SendButtonCover).css("display", "block");
      return true;
    }
    else {
      return false;
    }
  },

  ValidateCompose: function(FormID, btnId) {
    $("#" + FormID).validate({
      rules: {
        RecieverName: {
          required: true
        },
        Subject: {
          required: true
        },
        Body: {
          required: true
        }
      },
      messages: {
        RecieverName: {
          required: "Please include recipient for this message."
        },
        Subject: {
          required: "You must enter subject."
        },
        Body: {
          required: "You must enter message."
        }
      }
    });
    if ($("#" + FormID).valid()) {
      $("#divSendButtonCover").css("display", "block");
      return true;
    }
    else {
      return false;
    }
  },

  ValidateNote: function(FormID) {
    $("#" + FormID).validate({
      rules: {
        Subject: {
          required: true
        },
        Body: {
          required: true
        }
      },
      messages: {
        Subject: {
          required: "You must enter subject."
        },
        Body: {
          required: "You must enter message."
        }
      }
    });
    if ($("#" + FormID).valid()) {
      return true;
    }
    else {
      return false;
    }
  },

  MoveMessagesAction: function(Action, HiddenFieID, SubmitButtonID) {
    if (Common.IsCheckBoxChecked()) {
      if (Action == 3) {
        jConfirm('Are you sure you want to delete selected message(s).', 'Confirm Delete', function(result) {
          if (result) {
            $('#' + HiddenFieID).val(Action);
            $('#' + SubmitButtonID).trigger('click');
          }
        });
      }
      else {
        $('#' + HiddenFieID).val(Action);
        $('#' + SubmitButtonID).trigger('click');
      }
    } else
      jAlert('Please select message(s).');
  },

  MoveMessAction: function(Action, HiddenFieID, SubmitButtonID) {
    if (Action == 3) {
      jConfirm('Are you sure you want to delete message.', 'Confirm Delete', function(result) {
        if (result) {
          $('#' + HiddenFieID).val(Action);
          $('#' + SubmitButtonID).trigger('click');
        }
      });
    }
    else {
      $('#' + HiddenFieID).val(Action);
      $('#' + SubmitButtonID).trigger('click');
    }
  },

  DeleteMessagesAction: function(HiddenFieID, MsgID, SubmitButtonID) {
    jConfirm('Are you sure you want to delete this message.', 'Confirm Delete', function(result) {
      if (result) {
        $('#' + HiddenFieID).val(MsgID);
        $('#' + SubmitButtonID).trigger('click');
      }
    });
  },

  DeleteSingleDraft: function(HiddenFieID, MsgID, SubmitButtonID) {
    jConfirm('Are you sure you want to discard this draft.', 'Confirm Discard', function(result) {
      if (result) {
        $('#' + HiddenFieID).val(MsgID);
        $('#' + SubmitButtonID).trigger('click');
      }
    });

  },

  DeleteDraftDetail: function(SubmitButtonID) {
    jConfirm('Are you sure you want to discard this draft.', 'Confirm Discard', function(result) {
      if (result) {
        $('#' + SubmitButtonID).trigger('click');
      }
    });
  },

  DeleteMultipleDraft: function(SubmitButtonID) {
    if (Common.IsCheckBoxChecked()) {
      jConfirm('Are you sure you want to discard selected drafts.', 'Confirm Discard', function(result) {
        if (result) {
          $('#' + SubmitButtonID).trigger('click');
        }
      });
    } else
      jAlert('Please select drafts(s).');
  },

  AttachPhoto: function(fileuploadsectionID, cancelattchmentID, hfileuploadstate) {
    $('#' + cancelattchmentID).show();
    $('#' + fileuploadsectionID).show();
    $('#' + hfileuploadstate).val('1');
  },

  CloseAttachment: function(fileuploadsectionID, cancelattchmentID, hfileuploadstate, uploadcontrol) {
    $('#' + cancelattchmentID).hide();
    $('#' + fileuploadsectionID).hide();
    $('#' + hfileuploadstate).val('0');
    Message.ClearBrowseContent(uploadcontrol);
  },

  RemoveComposeDraftAttachment: function(preattachment, photovideosection) {
    $('#' + preattachment).hide();
    $('#' + photovideosection).show();
    $('#' + ComposeMessageControls.DraftFileAttached).val('0');
  },

  ResetComposeSuccessMessage: function() {
    var isDraft = ($('#' + ComposeMessageControls.SaveAsDraft).val() == 1);
    if (isDraft) {
      $('.ComposeMessageSent').each(function() { $(this).hide(); });
      $('.ComposeMessageSaved').each(function() { $(this).show(); });
    }
    else {
      $('.ComposeMessageSent').each(function() { $(this).show(); });
      $('.ComposeMessageSaved').each(function() { $(this).hide(); });
    }
  },

  SubmitComposeMessage: function() {
    if ($('#' + ComposeMessageControls.hTargetMember).val().length == 0)
      $('#' + ComposeMessageControls.RecieverName).val('');
    Message.ResetComposeSuccessMessage();
    $('#' + ComposeMessageControls.FileUploadErrorId).html('');
    if (Message.ValidateCompose(ComposeMessageControls.FormComposeMessage, ComposeMessageControls.BtnComposeMessageInner)) {
      if ($('#' + ComposeMessageControls.hUploadFileStateID).val() == "1" && $('#' + ComposeMessageControls.UploadingInputId).val().length > 0) {
        {
          $("#" + ComposeFileUploaderData.UploadingImage).show();
          $('#' + ComposeMessageControls.BtnSubmitAttachmentID).trigger('click');
        }
      }
      else {
        if ($('#' + ComposeMessageControls.DraftFileAttached).val() != '1')
          $('#' + ComposeMessageControls.AttachFileNameID).val('');
        $('#' + ComposeMessageControls.BtnComposeMessageInner).trigger('click');
      }
    }
    return false;
  },

  SubmitDraftComposeMessage: function() {
    if ($('#' + ComposeMessageControls.hTargetMember).val().length == 0)
      $('#' + ComposeMessageControls.RecieverName).val('');
    Message.ResetComposeSuccessMessage();
    $('#' + ComposeMessageControls.FileUploadErrorId).html('');

    if ($('#' + ComposeMessageControls.hUploadFileStateID).val() == "1" && $('#' + ComposeMessageControls.UploadingInputId).val().length > 0) {
      $("#" + ComposeFileUploaderData.UploadingImage).show();
      $('#' + ComposeMessageControls.BtnSubmitAttachmentID).trigger('click');
    }

    else {
      $('#' + ComposeMessageControls.AttachFileNameID).val('');
      $('#' + ComposeMessageControls.AttachActualFileNameID).val('');
      $('#' + ComposeMessageControls.BtnComposeMessageInner).trigger('click');
    }
    return false;
  },

  OnComposeAttachmentUploadSuccess: function(response) {
    var param = response.split('#');
    var result = { filename: param[0], exception: param[1], error: param[2], fileactualname: param[3] };
    if (result.exception.length == 0) {
      if (result.error.length > 0 && result.filename.length == 0) {
        $('#' + ComposeMessageControls.FileUploadErrorId).html(result.error);
        $("#" + ComposeMessageControls.SendButtonCover).hide();
      }
      else {
        if (result.error != "nofile") {
          $('#' + ComposeMessageControls.AttachFileNameID).val(result.filename);
          $('#' + ComposeMessageControls.AttachActualFileNameID).val(result.fileactualname);
        }
        else {
          $('#' + ComposeMessageControls.AttachFileNameID).val('');
          $('#' + ComposeMessageControls.AttachActualFileNameID).val('');
        }
        $('#' + ComposeMessageControls.BtnComposeMessageInner).trigger('click');
      }
    }
    else {
      $('#' + ComposeMessageControls.FileUploadErrorId).html("error uploading file.");
    }
  },

  SubmitMessageReply: function() {
    $('#' + ReplyMessageControl.FileUploadErrorId).html('')
    if (Message.ValidateReply(ReplyMessageControl.FormReplyMessage)) {
      var state = $('#' + ReplyMessageControl.hUpoadFileStateID).val();
      var file = $('#' + ReplyMessageControl.UploadingInputId).val();
      if (state == "1" && file.length > 0) {
        {
          $("#" + ReplyFileUploaderData.UploadingImage).show();
          $('#' + ReplyMessageControl.BtnSubmitAttachmentID).trigger('click');
        }
      }
      else {
        if ($('#' + ReplyMessageControl.DraftFileAttached).val() != '1')
          $('#' + ReplyMessageControl.AttachFileNameID).val('');
        $('#' + ReplyMessageControl.BtnReplyInner).trigger('click');
      }
    }
    return false;
  },

  SubmitDraftMessageReply: function() {
    $('#' + ReplyMessageControl.FileUploadErrorId).html('')
    var state = $('#' + ReplyMessageControl.hUpoadFileStateID).val();
    var file = $('#' + ReplyMessageControl.UploadingInputId).val();
    if (state == "1" && file.length > 0) {
      {
        $("#" + ReplyFileUploaderData.UploadingImage).show();
        $('#' + ReplyMessageControl.BtnSubmitAttachmentID).trigger('click');
      }
    }
    else {
      if ($('#' + ReplyMessageControl.DraftFileAttached).val() != '1')
        $('#' + ReplyMessageControl.AttachFileNameID).val('');
      $('#' + ReplyMessageControl.BtnReplyInner).trigger('click');
    }

    return false;
  },

  OnReplyAttachmentUploadSuccess: function(response) {
    $('#' + ReplyMessageControl.SendButtonCover).hide();
    var param = response.split('#');
    var result = { filename: param[0], exception: param[1], error: param[2], fileactualname: param[3] };

    if (result.exception.length == 0) {
      if (result.error.length > 0 && result.filename.length == 0) {
        $('#' + ReplyMessageControl.FileUploadErrorId).html(result.error);
      }
      else {
        if (result.error != "nofile")
          $('#' + ReplyMessageControl.AttachFileNameID).val(result.filename);
        else
          $('#' + ReplyMessageControl.AttachFileNameID).val('');

        Message.ClearBrowseContent(ReplyMessageControl.UploadingInputId);

        if ($('#' + ReplyMessageControl.SaveAsDraft).val() == '1')
          Message.ReplyDraftUploadSucces(result.filename, result.fileactualname);
        else {
          Message.ReplyUploadSucces(result.filename, result.fileactualname);
        }

        $('#' + ReplyMessageControl.BtnReplyInner).trigger('click');
      }
    }
    else {
      $('#' + ReplyMessageControl.FileUploadErrorId).html("error uploading file.");
    }
  },

  ReplyDraftUploadSucces: function(filename, actualFileName) {
    $('#' + ReplyMessageControl.AttachFileNameID).val(filename);
    $('#' + ReplyMessageControl.AttachActualFileNameID).val(actualFileName);
    $('#' + ReplyMessageControl.DraftAttachedFileName).attr('src', ReplyMessageControl.ThumbUrl + filename);
    $('#' + ReplyMessageControl.DraftAttachmentSection).show();
    $('#' + ReplyMessageControl.ReplyAttachmentSection).hide();
    Message.CloseAttachment(ReplyMessageControl.ReplyInputSection, ReplyMessageControl.CancelSection, ReplyMessageControl.hUpoadFileStateID, ReplyMessageControl.UploadingInputId);
    $('#' + ReplyMessageControl.DraftFileAttached).val('1');
  },

  ReplyUploadSucces: function(filename, actualFileName) {
    $('#' + ReplyMessageControl.AttachFileNameID).val(filename);
    $('#' + ReplyMessageControl.AttachActualFileNameID).val(actualFileName);
    $('#' + ReplyMessageControl.DraftAttachedFileName).removeAttr('scr');
    $('#' + ReplyMessageControl.DraftAttachmentSection).hide();
    $('#' + ReplyMessageControl.ReplyAttachmentSection).show();
    $('#' + ReplyMessageControl.DraftFileAttached).val('0');
  },

  ReplyResposeComplete: function(content, UpdateTargetId, DraftStatusId, LoginContent, DraftSuccessContent, DraftFailureContent) {
    $('#' + DraftStatusId).hide();
    if (content != LoginContent) {
      if (content != DraftSuccessContent && content != DraftFailureContent) {
        $("#" + UpdateTargetId).before(content);
      }
      else {
        $('#' + DraftStatusId).html(content);
        $('#' + DraftStatusId).show();
      }
    }

  },


  RemoveReplyDraftAttachment: function(preattachment, photovideosection) {
    $('#' + preattachment).hide();
    $('#' + photovideosection).show();
    $('#' + ReplyMessageControl.DraftFileAttached).val('0');
    Message.AttachPhoto(ReplyMessageControl.ReplyInputSection, ReplyMessageControl.CancelSection, ReplyMessageControl.hUpoadFileStateID);
  },


  ClearBrowseContent: function(control) {
    var browse = document.getElementById(control);
    var newbrowse = browse.cloneNode(false);
    browse.parentNode.replaceChild(newbrowse, browse);
    $('#' + control).val('');
  },

  BeforeAttachmentSubmit: function() {
    return true;
  },

  ReconstructComposeMessageURL: function(searchBoxId) {
    keyword = $('#' + searchBoxId).val();
    var keepKeword = keyword != 'Search Messages';
    var key = 'Keyword';
    var msLink = $('a[class*=thickbox][rev*=composemessage]');
    var url = $(msLink).attr("rev");
    var urlparts = url.split('?');
    var hasReplaced = false;

    if (urlparts.length == 2) {
      var params = urlparts[1].split('&');
      urlparts[1] = '';
      for (var c = 0; c < params.length; c++) {
        if (params[c].startsWith(key)) {
          params[c] = keepKeword ? key + '=' + keyword : '';
          hasReplaced = true;
        }
        if (params[c] != null && params[c].length > 0) {
          var saparator = c > 0 && c < params.length ? '&' : '';
          urlparts[1] = urlparts[1] + saparator + params[c];
        }
      }
    }

    if (hasReplaced)
      $(msLink).attr('rev', urlparts[0] + "?" + urlparts[1])
    else
      $(msLink).attr('rev', urlparts[0] + "?" + urlparts[1] + (keepKeword ? '&' + key + '=' + keyword : ''));
  },

  TypeMessAction: function(URL, HiddenFieID, Action) {
    if ($('#txtSearchMessagesBox').val().trim() != 'Search Messages' && $('#txtSearchMessagesBox').val().trim() != '')
      URL += "?Keyword=" + $('#txtSearchMessagesBox').val().trim();
    $('#' + HiddenFieID).val(Action);
    window.location.href = URL;
  },

  RedirectURL: function(RedirectURL) {
    document.location.href = RedirectURL;
  },

  SetFolderOption: function(HiddenFieID, URLToHit, Action, Keyword) {
    $('#' + HiddenFieID).val(Action);
    if ($('#txtSearchMessagesBox').val().trim() != 'Search Messages' && $('#txtSearchMessagesBox').val().trim() != '') {
      SWFAddress.setValue(URLToHit + Keyword + $('#txtSearchMessagesBox').val());

    } else {
      SWFAddress.setValue(URLToHit);
    }
  },

  SearchAllConnections: function(SearchBoxID, SeacrhDefaultValue, URLToHit_Inbox, URLToHit_Inbox_Read, URLToHit_Inbox_UnRead, URLToHit_Sent, URLToHit_Draft) {
    if ($('#' + SearchBoxID).val().trim() != SeacrhDefaultValue && $('#' + SearchBoxID).val().trim() != '') {
      if ($('#hdnFolderMessage').val() == 1) {
        if ($('#hdnTypeMessage').val().trim() == 1) //Inbox
          SWFAddress.setValue(URLToHit_Inbox + $('#' + SearchBoxID).val());
        else if ($('#hdnTypeMessage').val().trim() == 2)//Inbox_Read
          SWFAddress.setValue(URLToHit_Inbox_Read + $('#' + SearchBoxID).val());
        else if ($('#hdnTypeMessage').val().trim() == 3)//Inbox_UnRead
          SWFAddress.setValue(URLToHit_Inbox_UnRead + $('#' + SearchBoxID).val());
      } else if ($('#hdnFolderMessage').val() == 2) {
        SWFAddress.setValue(URLToHit_Sent + $('#' + SearchBoxID).val());
      } else if ($('#hdnFolderMessage').val() == 3) {
        SWFAddress.setValue(URLToHit_Draft + $('#' + SearchBoxID).val());
      }
    }
    else {
      if ($('#hdnFolderMessage').val() == 1) {
        if ($('#hdnTypeMessage').val().trim() == 1)//Inbox
          SWFAddress.setValue(URLToHit_Inbox);
        else if ($('#hdnTypeMessage').val().trim() == 2)//Inbox_Read
          SWFAddress.setValue(URLToHit_Inbox_Read);
        else if ($('#hdnTypeMessage').val().trim() == 3)//Inbox_UnRead
          SWFAddress.setValue(URLToHit_Inbox_UnRead);
      } else if ($('#hdnFolderMessage').val() == 2) {
        SWFAddress.setValue(URLToHit_Sent);
      } else if ($('#hdnFolderMessage').val() == 3) {
        SWFAddress.setValue(URLToHit_Draft);
      }
    }
    Message.ReconstructComposeMessageURL(SearchBoxID);
  },

  SendSucess: function(FormDivID, MessageDivID) {
    $('#' + FormDivID).hide();
    $('#' + MessageDivID).show();
    Common.InitilizeAllComponents();
  },

  ToggleVisibility: function(elem, action) {
    if (action == 1)
      $('#' + elem).show();
    else
      $('#' + elem).hide();
  }
}


AIM = {

  frame: function(c) {

    var n = 'f' + Math.floor(Math.random() * 99999);
    while (($('#' + n).is('*')))
      n = 'f' + Math.floor(Math.random() * 99999);

    var d = document.createElement('DIV');
    d.innerHTML = '<iframe style="display:none" src="about:blank" id="' + n + '" name="' + n + '" onload="AIM.loaded(\'' + n + '\')"></iframe>';
    document.body.appendChild(d);

    var i = document.getElementById(n);
    if (c && typeof (c.onComplete) == 'function') {
      i.onComplete = c.onComplete;
    }

    return n;
  },

  form: function(f, name) {
    f.setAttribute('target', name);
  },

  submit: function(f, c) {
    AIM.form(f, AIM.frame(c));
    if (c && typeof (c.onStart) == 'function') {
      return c.onStart();
    } else {
      return true;
    }
  },

  loaded: function(id) {
    var i = document.getElementById(id);
    if (i.contentDocument) {
      var d = i.contentDocument;
    } else if (i.contentWindow) {
      var d = i.contentWindow.document;
    } else {
      var d = window.frames[id].document;
    }
    if (d.location.href == "about:blank") {
      return;
    }

    if (typeof (i.onComplete) == 'function') {
      i.onComplete(d.body.innerHTML);
    }
  }

}

var Articles =
{
  AllCommentsSubmit: function(Action, HiddenFieID, SubmitButtonID) {
    $('#' + HiddenFieID).val(Action);
    $('#' + SubmitButtonID).trigger('click');
  },

  HideDiv: function(ViewAllComments, ViewLessComments) {
    Common.ToggleDivVisibility(ViewAllComments);
    Common.ToggleDivVisibility(ViewLessComments);
  },

  ValidateComment: function(FormID, text) {
    $.validator.addMethod(
            "CommentValue",
            function(value, element) {
              var re = new RegExp('[<>](.*?)$');
              return this.optional(element) || (!(re.test(value)) && document.getElementById(element.id).value != 'Write a comment ...');
            },
            "You must enter valid comment."
        );

    $("#" + FormID).validate({
      rules: {
        Comment: {
          required: true,
          CommentValue: true
        }
      },
      messages: {
        Comment: {
          required: "You must write comment."
        }
      }
    });
    if ($("#" + FormID).valid()) {

      return true;
    }
    else {
      return false;
    }
  }
}

var FriendRequest =
{
  AcceptSucceed: function(ID, FormDivID, MessageDivID) {
    $('#' + ID).trigger('click');
    $('#' + FormDivID).hide();
    $('#' + MessageDivID).show();
    Common.InitilizeAllComponents();
  },

  IgnoreSucceed: function(ID, FormDivID, MessageDivID) {
    $('#' + ID).trigger('click');
    $('#' + FormDivID).hide();
    $('#' + MessageDivID).show();
    Common.InitilizeAllComponents();
  },

  ValidateAcceptRequest: function(FormID) {
    $("#" + FormID).validate({
      rules: {
        ddlFolderID: {
          required: true
        }
      },
      messages: {
        ddlFolderID: {
          required: "You must select folder name."
        }
      }
    });

    if ($("#" + FormID).valid()) {
      return true;
    }
    else {
      return false;
    }
  },

  ValidateSendingRequest: function(FormID) {
    $("#" + FormID).validate({
      rules: {
      Captcha:
      {
        required: true
      },
        ddlFolderID: {
          required: true
        },
        Captcha: {
          required: true
        }
      },
      messages: {
      Captcha: {
          required: "You must enter security code."
        },
        ddlFolderID: {
          required: "You must select folder name."
        },
        Captcha: {
          required: "You must enter security code"
        }
      }
    });

    if ($("#" + FormID).valid()) {
      return true;
    }
    else {
      return false;
    }
  }
}

var Tab =
{
  BindLeftNavigation: function(BtnID) {
    $('#' + BtnID).trigger('click');
    Common.InitilizeAllComponents();
  }
}

var Register =
{
  Validate: function(FormID, USAID) {

    $.validator.addMethod(
            "regexName",
            function(value, element) {
              var re = new RegExp('^[a-zA-Z0-9]*$');
              return this.optional(element) || re.test(value);
            },
            "You must specify valid screen name."
        );
    $.validator.addMethod(
            "regexfname",
            function(value, element) {
              var re = new RegExp('^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$');
              return !re.test(value);
            },
            "You must specify valid first name."
        );
    $.validator.addMethod(
            "regexlname",
            function(value, element) {
              var re = new RegExp('^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$');
              return !re.test(value);
            },
            "You must specify valid last name."
        );

    $.validator.addMethod(
            "checkValidDate",
            function(value, element) {
              if ($("#MonthID").attr("selectedIndex") == 0 || $("#DayID").attr("selectedIndex") == 0 || $("#YearID").attr("selectedIndex") == 0) {
                $("#lblValidateBirthday").show();
                return false;
              }
              else {
                var dayobj = new Date($("#YearID").val(), $("#MonthID").val() - 1, $("#DayID").val())
                if ((dayobj.getMonth() + 1 != $("#MonthID").val()) || (dayobj.getDate() != $("#DayID").val()) || (dayobj.getFullYear() != $("#YearID").val())) {
                  $("#lblValidateBirthday").show();
                  return false;
                }
                else {
                  $("#lblValidateBirthday").hide();
                  return true;
                }
              }
            },
            ""
        );

    $.validator.addMethod(
            "requiredCaptcha",
            function(value, element) {
              if ($("#recaptcha_response_field").val().trim() == '') {
                $('#lblValidateCaptcha').show();
                return false;
              }
              else {
                $('#lblValidateCaptcha').hide();
                return true;
              }
            },
            ""
        );

    $.validator.addMethod(
            "requiredGender",
            function(value, element) {
              if ($('#chkMale').is(':checked') != true && $('#chkFemale').is(':checked') != true) {
                $("#lblValidateGender").show();
                return false;
              }
              else {
                $("#lblValidateGender").hide();
                return true;
              }
            },
            ""
        );

    $.validator.addMethod(
            "requiredTerms",
            function(value, element) {
              if ($('#Terms').is(':checked') != true) {
                $("#lblValidateTerms").show();
                return false;
              }
              else {
                $("#lblValidateTerms").hide();
                return true;
              }
            },
            ""
        );

    $.validator.addMethod(
            "requiredPassword",
            function(value, element) {
              if ($("#Password").val().trim() == '') {
                $('#lblValidateReqPassword').show();
                $('#lblValidateMaxLengthPassword').hide();
                return false;
              }
              else if ($("#Password").val().trim() != '' && $("#Password").val().trim().length < 5) {
                $('#lblValidateMaxLengthPassword').show();
                $('#lblValidateReqPassword').hide();
                return false;
              }
              else {
                $('#lblValidateReqPassword').hide();
                $('#lblValidateMaxLengthPassword').hide();
                return true;
              }
            },
            ""
        );

    $("#" + FormID).validate({
      rules: {
        YearID: {
          checkValidDate: true
        },
        MonthID: {
          checkValidDate: true
        },
        DayID: {
          checkValidDate: true
        },
        FirstName: {
          required: true,
          regexfname: true
        },
        LastName: {
          required: true,
          regexlname: true
        },
        ScreenName: {
          required: true,
          regexName: true
        },
        EmailAddress: {
          required: true,
          email: true
        },
        Password: {
          requiredPassword: true
        },
        recaptcha_response_field: {
          requiredCaptcha: true
        },
        MaleOrFemale: {
          requiredGender: true
        },
        Terms: {
          requiredTerms: true
        }
      },
      messages: {
        YearID: {
          checkValidDate: ""
        },
        MonthID: {
          checkValidDate: ""
        },
        DayID: {
          checkValidDate: ""
        },
        FirstName: {
          required: "You must specify first name.",
          regexfname: "You must specify valid first name."
        },
        LastName: {
          required: "You must specify last name.",
          regexlname: "You must specify valid last name."
        },
        ScreenName: {
          required: "You must specify screen name."
        },
        EmailAddress: {
          required: "You must specify email address.",
          email: "You must specify valid email address."
        },
        Password: {
          requiredPassword: ""
        },
        recaptcha_response_field: {
          requiredCaptcha: ""
        },
        MaleOrFemale: {
          requiredGender: ""
        },
        Terms: {
          requiredTerms: ""
        }
      }
    });

    $("span.serverMsg").each(function() {
      $(this).remove();
    });

    if ($("#" + FormID).valid()) {
      $("#Password_bar").show();
      $("#Password_text").show();
      return true;
    }
    else {
      return false;
    }
  }
}

var Password =
{
  ValidateForgotPassword: function(FormID) {
    $("#" + FormID).validate({
      rules: {
        EmailForgot: {
          required: true,
          email: true
        }
      },
      messages: {
        EmailForgot: {
          required: "You must specify email address.",
          email: "You must specify valid email address."
        }
      }
    });

    if ($("#" + FormID).valid()) {
      return true;
    }
    else {
      return false;
    }
  }
}

var Search =
{
  EditShow: function(id) {//show edit section
    $("#divSearchInfo" + id).hide();
    $("#divSearchInfo" + id + "Edit").show();
  },

  EditHide: function(id) {//edit edit section
    $("#divSearchInfo" + id).show();
    $("#divSearchInfo" + id + "Edit").hide();
  },

  ValidateSave: function(FormID) {
    $("#" + FormID).validate({
      rules: {
        Name: {
          required: true
        }
      },
      messages: {
        Name: {
          required: "You must specify name."
        }
      }
    });

    if ($("#" + FormID).valid()) {
      Search.SetFields();
      return true;
    }
    else {
      return false;
    }
  },

  ValidateSearch: function(FormID, SearchURL) {
    Search.SetFields();
    Search.SetMultiSelects();
    document.forms[FormID].action = SearchURL;
    document.forms[FormID].method = "POST";
    document.forms[FormID].submit();
  },

  SetFields: function() {
    // Checking Height
    if ($("#FuturePartnerHeightFeetFromID").val() > $("#FuturePartnerHeightFeetToID").val()) {
      document.getElementById("FuturePartnerHeightFeetFromID").selectedIndex = 0;
    }
    else if ($("#FuturePartnerHeightFeetFromID").val() <= $("#FuturePartnerHeightFeetToID").val() && $("#FuturePartnerHeightInchesFromID").val() > $("#FuturePartnerHeightInchesToID").val()) {
      document.getElementById("FuturePartnerHeightInchesFromID").selectedIndex = 0;
    }

    // Checking Age
    if ($("#FuturePartnerAgeFromID").val() > $("#FuturePartnerAgeToID").val()) {
      document.getElementById("FuturePartnerAgeFromID").selectedIndex = 0;
    }
  },

  SetMultiSelects: function() {
    $("select[multiple]").each(function() {
      if (this.selectedIndex == 0) {
        this.selectedIndex = -1;
      }
    });
  },

  GenerateSelectedCriteria: function() {
    $("select[multiple]").each(function() {
      $('#' + this.id).change(function() {
        Common.ValidateNoPreference(this);
        $('#div' + this.id).remove();
        if (this.selectedIndex > 0) {
          var htmlToAppend = '';
          htmlToAppend += '<div id="div' + this.id + '">';
          htmlToAppend += '<p class="leftp_prvtView_borderB mTop10">';
          htmlToAppend += $('#lbl' + this.id).html();
          htmlToAppend += '</p>';
          htmlToAppend += '<ul class="left_ul_search">';
          for (var i = 1; i < this.options.length; i++) {
            if (this.options[i].selected) {
              htmlToAppend += '<li id="li' + this.id + i.toString() + '">';
              htmlToAppend += '<a onclick="Search.RemoveOption(\'li' + this.id + i.toString() + '\', \'' + this.id + '\',' + i + ')" class="closed_search" href="javascript:;">&nbsp;</a>';
              htmlToAppend += '<span class="float_left">' + this.options[i].innerHTML + '</span>';
              htmlToAppend += '</li>';
            }
          }
          htmlToAppend += '</ul>';
          htmlToAppend += '</div>'
          $('#divSelectedCritireaDetails').append(htmlToAppend);
        }
      });
    });
  },

  GenerateRandomSelection: function() {
    var createCounter = 0;
    var htmlToAppend = '';
    htmlToAppend += '<div class="leftp_top_crnr"><h3>Your Search Criteria</h3></div>';
    htmlToAppend += '<div class="leftp_prvtView_middle_new">';
    $("select[multiple], select.RandomSel").each(function() {
      Common.ValidateNoPreference(this);
      if (this.selectedIndex > 0) {
        createCounter++;
        htmlToAppend += '<div id="div' + this.id + '">';
        htmlToAppend += '<p class="leftp_prvtView_borderB mTop10">';
        htmlToAppend += $('#lbl' + this.id).html();
        htmlToAppend += '</p>';
        htmlToAppend += '<ul class="left_ul_search">';
        for (var i = 1; i < this.options.length; i++) {
          if (this.options[i].selected) {
            htmlToAppend += '<li>';
            htmlToAppend += '<a onclick="Search.RemoveOption(\'' + this.id + '\',' + i + ')" class="closed_search" href="javascript:;">&nbsp;</a>';
            htmlToAppend += '<span class="float_left paddLft8">' + this.options[i].innerHTML + '</span>';
            htmlToAppend += '</li>';
          }
        }
        htmlToAppend += '</ul>';
        htmlToAppend += '</div>';
      }
    });
    htmlToAppend += '</div>';
    htmlToAppend += '<div class="leftp_bottom_crnr">&nbsp;</div>';
    if (createCounter > 0) {
      $('#divRandomSelection').html(htmlToAppend);
      createCounter = 0;
    }
    else {
      $('#divRandomSelection').html('');
    }
  },

  RemoveOption: function(ddlID, optionIndex) {
    if ($('#' + ddlID).attr("multiple"))
      document.getElementById(ddlID).options[optionIndex].selected = false;
    else
      document.getElementById(ddlID).selectedIndex = 0;
    Search.GenerateRandomSelection();
  },

  BindSearchSelectedCriteria: function() {
    Search.GenerateRandomSelection();
    $("select[multiple], select.RandomSel").each(function() {
      $('#' + this.id).change(function() {
        Search.GenerateRandomSelection();
      });
    });
  },

  Delete: function(FormID) {
    document.forms[FormID].submit();
  }
}

var Pagination =
{
  Post: function(FormID, PostURL) {
    document.forms[FormID].action = PostURL;
    document.forms[FormID].method = "POST";
    document.forms[FormID].submit();
  }
}

var Contact =
{
  Validate: function(FormID) {
    $("#" + FormID).validate({
      rules: {
        Email: {
          required: true,
          email: true
        },
        Subject: {
          required: true
        },
        Message: {
          required: true,
          maxlength: 1000
        }

      },
      messages: {
        Email: {
          required: "You must specify email address.",
          email: "You must specify valid email address."
        },
        Subject: {
          required: "You must specify subject."
        },
        Message: {
          required: "You must specify message.",
          maxlength: "Maximum 1000 Characters."
        }
      }
    });

    if ($("#" + FormID).valid()) {
      return true;
    }
    else {
      return false;
    }
  }
}

var SuggestionBox =
{
  Validate: function(FormID) {
    $("#" + FormID).validate({
      rules: {
        Email: {
          required: true,
          email: true
        },
        Message: {
          required: true,
          maxlength: 1000
        }

      },
      messages: {
        Email: {
          required: "You must specify email address.",
          email: "You must specify valid email address."
        },
        Message: {
          required: "You must specify message.",
          maxlength: "Maximum 1000 Characters."
        }
      }
    });

    if ($("#" + FormID).valid()) {
      return true;
    }
    else {
      return false;
    }
  }
}

var SignIn =
{
  SetHashURL: function() {//show edit section
    document.getElementById('hashURL').value = window.location.hash;
  }
}