﻿/// <reference path="jquery-1.2.6-vsdoc.js" />
/// <reference path="jq-extensions.js" />

//Global vars, don't use unless you made them
var pagerLoadedPage = false; 
var searchPageLoaded = false;

function collapseContent(containerID, contentID, actorID, descriptionLength, moreText, lessText) {
    /// <summary>
    /// Create a collapsible/expandable content section to hide/show long descriptions.
    /// </summary>
    /// <param name="containerID">The Parent container holding the content and the action link.</param>
    /// <param name="contentID">The container holding the content which will be expanded/collapsed.</param>
    /// <param name="actorID">The object being clicked to expand/collapse the content.</param>
    /// <param name="descriptionLength">The amount of the description to show while collapsed.</param>
    /// <param name="moreText">The text the "more" action will display</param>
    /// <param name="lessText">The text the "less" action will display</param>
    $(containerID + " " + contentID).each(function(i) {
        if ($(this).attr("id") == "") {
            $(contentID).each(function(x) {
                if ($("body").find("#content" + x).length > 0) {
                    i = x + 1;
                }
            });

           
            var totalContent = $(this).text().length;
            
                                                               
            if (totalContent > descriptionLength) {
               var tag = this.tagName;
               var className = $(this).attr("class");
               var shortContent = ($(this).text()).substr(0, descriptionLength);
               var lastSpace = shortContent.lastIndexOf(' ');
               shortContent = shortContent.substr(0, lastSpace) + "...";
               
               var shortC = $("<" + tag + " id='short" + i + "' class='" + className + "'>" + shortContent + "</" + tag + ">");
               $(this).after(shortC);

                $(this).hide().attr("id", "content" + i);

                $(this).parents(containerID).find(actorID).click(function() {

                    if ($("#content" + i + ":hidden").length > 0) {
                        $("#content" + i).show();
                        $("#short" + i).hide();
                        $(this).text(lessText);
                        $(containerID).removeClass("containerHeight");
                    }
                    else {
                        $("#content" + i).hide();
                        $("#short" + i).show();
                        $(this).text(moreText);                        
                        $(containerID).addClass("containerHeight");
                    }

                    return false;
                });
                
            } else { $(this).parents(containerID).find(actorID).hide(); }            
        }
    });
}

function loadCampaigns(containerID, actor) {
    /// <summary>
    /// Allows the loading of campaigns through Ajax.
    /// </summary>
    /// <param name="containerID">The Element the Campaigns will be loaded into.</param>

    var sortOrder = $(actor).text();
    sortOrder = $.trim(sortOrder);

    $(containerID).load("/Campaign/SortCampaigns/1?sortOrder=" + sortOrder);
}
function loadCampaignsBySet(actor, range, lastItem) {
    /// <summary>
    /// Creates Campaign Loading Querystring
    /// </summary>
    /// <param name="containerID">The Element the Campaigns will be loaded into.</param>
    /// <param name="lastIndex">The int index of the last campaign that was output</param>
    /// <param name="range">Int amount of campaigns to output</param>
    loadComplete = false;    

    
    var sortOrder = $(actor).text();
    sortOrder = $.trim(sortOrder);

    var campQueryString = "/Campaign/GetCampaignsBySet/1?sortOrder=" + sortOrder + "&";
    campQueryString += "returnAmount=" + range + "&";
    campQueryString += "lastItem=" + lastItem;

    return campQueryString;

}

function TrimString(sInString) {
    sInString = sInString.replace(/^\s+/g, ""); // strip leading
    return sInString.replace(/\s+$/g, ""); // strip trailing
}
function contentSeek(container) {
    var scrollDist = $(container).innerHeight() + $(container).scrollTop();
    if (($(container).getContentHeight("div.wrapper") - scrollDist) <= 0) {
        $(container).moreContent(".tempCampaigns")
    }
}
function startWait() {

    var topCenter = $(document).height() / 2;
    var leftCenter = $(document).width() / 2;
    $(".progressBar")
                    .data("loading", true)
                    .css("position", "absolute")
                    .css("top", topCenter)
                    .css("left", leftCenter)
                    .show();
}
function stopWait() {
    $(".progressBar")
                    .hide()
                    .data("loading", false);
}

function LoadModalForm(url) {
    /// <summary>
    /// Loads the Modal login window into the browser.
    /// </summary>
    $.modal.close();
    $("#ModalWrapper").modal({ overlay : 90, onShow: function (dialog) { $("#modalContainer").css("position", "absolute"); } });
    $("#ModalWrapper").load(url);    
}

function LoadPopupForm(url) {
    /// <summary>
    /// Loads the Modal login window into the browser.
    /// </summary>
    $.modal.close();
    $("#ModalWrapper").modal({ overlay : 90 });
    $("#ModalWrapper").load(url);
}


function LoadLoginForm() {
    /// <summary>
    /// Loads the Modal login window into the browser.
    /// Will get the login control through an Ajax call.
    /// </summary>
   
    
        var date = new Date();
        $.modal.close();
        $("#ModalWrapper").modal({ overlay : 90 });    
        $("#ModalWrapper").load("/Member/RequestLogin?ajax=true&context="+escape(window.location.href)+"&"+date.getMilliseconds());
    
    
      
}

function LoadSubscriptionForm(url, clicked)
{
    /// <summary>
    /// Loads the Modal subscrible to thread window into the browser.
    /// Will get the subscribe to thread page through an Ajax call.
    /// </summary>
    $.modal.close();
    $("#ModalWrapper").modal({ overlay : 90/*, onShow: function (dialog) { $("#modalContainer").css("position", "absolute"); }*/ });
    $("#ModalWrapper").load(url, function(){
        setSubscriptionSender(clicked);
    });
}

    
function LoadInappropriateForum(url, clicked) {
    /// <summary>
    /// Loads the Modal login window into the browser.
    /// Will get the login control through an Ajax call.
    /// </summary>
    
    $.modal.close();
    $("#ModalWrapper").modal({ overlay : 90 });
    $("#ModalWrapper").load(url, function(){
		setInappropriateSender(clicked);
    });
}

function LoadInappropriateForm(url, clicked) {
    /// <summary>
    /// Loads the Modal login window into the browser.
    /// Will get the login control through an Ajax call.
    /// </summary>
    $.modal.close();
    $("#ModalWrapper").modal({ overlay : 90 });
    $("#ModalWrapper").load(url, { active: clicked}, function(){
        setVar(clicked);
    });
}

function LoadFileBrowser(ownerType, ownerId) {
    $("#ModalWrapper").modal({ overlay : 90, containerCss: { height: '550px', width: '958px', marginLeft: '-479px', top: '150px'} });
    $("#ModalWrapper").load("/Media/AsyncGetAttachedMedia", { type: ownerType,
                                                                 ownerGuid: ownerId });
}

function LoadPersonaForm(url) {
    /// <summary>
    /// Loads the Modal login window into the browser.
    /// Will get the login control through an Ajax call.
    /// </summary>
    $.modal.close();
    $("#ModalWrapper").modal({ overlay : 90 });
    $("#ModalWrapper").load(url);
    
      
}
function LoadLeaveCommentForm(campaignId, ideaId) {
    /// <summary>
    /// Loads the Modal login window into the browser.
    /// Will get the login control through an Ajax call.
    /// </summary>
    $.modal.close();
    $("#ModalWrapper").modal({ overlay : 90 });
    $("#ModalWrapper").load("/Campaign/LeaveComment?campaignId=" + campaignId + "&ideaId=" + ideaId);
}

function LoadEditCommentForm(campaignId, ideaId, commentId) {
    /// <summary>
    /// Loads the Modal login window into the browser.
    /// Will get the login control through an Ajax call.
    /// </summary>
    $.modal.close();
    $("#ModalWrapper").modal({ overlay : 90 });
    $("#ModalWrapper").load("/Campaign/EditComment?campaignId=" + campaignId + "&ideaId=" + ideaId + "&commentId=" + commentId);
}



function LoadRegistrationForm() {
    $.modal.close();

    if (authMethod == "NAID")
    {
        $("#ModalWrapper").modal({ overlay : 90, containerCss: { height: '500px', width: '750px', marginLeft: '-375px', top: '10%'} });
        $("#ModalWrapper").load("/Member/Registration?ajax=true");
    }
    else
    {
    LoadLoginForm();
    }
}

function LoadForgotPasswordForm() {
    $.modal.close();
    $("#ModalWrapper").modal({ overlay : 90, containerCss: { height: '150px', width: '550px', marginLeft: '-275px', top: '10%'} });
    $("#ModalWrapper").load("/Member/ForgotPassword?ajax=true");
}

function LoadContactUsForm() { 
    $.modal.close();
    $("#ModalWrapper").modal({ overlay : 90 });
    $("#ModalWrapper").load("/Client/ContactUs?isAjax=true");
}

function LoadTermsOfService() { 
    //$.modal.close();
    //$("#ModalWrapper").modal({ overlay : 90 });
    $("#Terms").load("/Client/Terms?isAjax=true");
}

function LoadEmbedForm(url) {
    $.modal.close();
    $("#ModalWrapper").modal({ overlay : 90 });
    $("#ModalWrapper").load("/Campaign/EmbedIdea?isAjax=true&embedURL=" + url);
}

function passwordStrength(password)

{
	var score  = 0;
	
	//if password bigger than 6 give 1 point		
	if (password.length > 6) score++;
	
	//if password has both lower and uppercase characters give 1 point		
	if ( ( password.match(/[a-z]/) ) && ( password.match(/[A-Z]/) ) ) score++;
	
	//if password has at least one number give 1 point
	if (password.match(/\d+/)) score++;

	//if password has at least one special caracther give 1 point
	if ( password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/) )	score++;

	//if password bigger than 12 give another 1 point
	if (password.length > 12) score++;

    return score;
}


function getHashValue(key, defaultTab) {
    /// <summary>
    /// Function to retrieve the value of a specific url hash key/value pair.
    /// </summary>
    /// <param name="key">Key of the specific tab we are looking for</param>
    /// <param name="defaultTab">Optional parameter to return if there is a default tab expected</param>
    var hashes = window.location.hash.replace("#", "").split("&"); 
    for (var i in hashes) {        
        valuePair = hashes[i].split("=");      
        if(valuePair[0] == key) return valuePair[1];
    } 
    
    return defaultTab;
}

function setHashValue(key, value) {
   var currentHash = window.location.hash;
   var keyExists = currentHash.indexOf(key);

   if (currentHash.length > 1) {
      if(keyExists > -1) {
         var nextValue = currentHash.indexOf('&', keyExists);
         var hashEnd = (nextValue == -1) ? currentHash.length : (nextValue - 1);
         var valueToReplace = currentHash.substr(keyExists, hashEnd);
         window.location.hash = currentHash.replace(valueToReplace, key + "=" + value);
      } else {
         window.location.hash = currentHash + "&" + key + "=" + value;
      }
   } else {
      window.location.hash = key + "=" + value;
   }
}

function clearHash() {
   window.location.hash = "#";
}

function DisplayValidation(data) {
    /// <summary>
    /// Function will display form validation results to any form following our standard behavior
    /// </summary>
    $(".errorText").text("");
    $(".formItem input").add(".formItem select").add(".formItem textarea").removeClass("invalid");
    $(".validator").hide();
    if (tinyMCE.activeEditor != null) {
        var mceEd = tinyMCE.activeEditor.getBody();
        $(mceEd).removeClass("invalid");
    }
    $.each(data, function(i, error) {
        
        if (tinyMCE.get(error.Key) == null) {                    
            var fieldId = "#" + error.Key;        
            $(fieldId).addClass("invalid");
            $(fieldId).parent().find(".errorText").append("<li>" + error.Response + "</li>");
        } else { 
            var ed = tinyMCE.get(error.Key);
            var edContainer = ed.getBody();
            var edReplaced = ed.getElement();

            $(edContainer).addClass("formItem invalid");
            $(ed.getDoc()).add(edContainer).mouseover(function() {
                $(".validator").hide();
                if ($(edReplaced).siblings(".validator").find(".errorText li").length > 0) {
                    $(edReplaced).siblings(".validator").show();
                }
            });
            $(edReplaced).parent().find(".errorText").append("<li>" + error.Response + "</li>");
            
        }
    });
    $(".formItem input").add(".formItem select").add(".formItem textarea").mouseover(function() {
        $(".validator").hide();
        if($(this).parent().find(".errorText li").length > 0) {
            $(this).parent().find(".validator").show();
        }
    });
    
}

function setupTinyMCE() {
    /// <summary>
    /// Sets up the TinyMCE editors by replacing textareas with class "mceMe" with the editor.
    /// </summary>
    tinyMCE_GZ.init({
        plugins: 'bbcode_na,media_na,inlinepopups',
        themes: 'advanced',
        languages: 'en',
        disk_cache: true,
        debug: false
    });

    tinyMCE.init({ 
        theme: "advanced", 
        mode: "specific_textareas",
        editor_selector: "mceMe",
        plugins: "bbcode_na,media_na,inlinepopups,maxlength_na",
        theme_advanced_buttons1: "bold,italic,underline,bullist,numlist,undo,redo,link,unlink,image,media,forecolor,blockquote,removeformat,code",
        theme_advanced_buttons2: "",
        theme_advanced_buttons3: "",
        theme_advanced_toolbar_location: "top",
        theme_advanced_toolbar_align: "left",
        //theme_advanced_styles: "Code=codeStyle,Quote=quoteStyle",
        theme_advanced_source_editor_width: 570,
        theme_advanced_source_editor_height: 320,
        content_css: "/Content/css/TinyMCEContent.css",
        entity_encoding: "raw",
        add_unload_trigger: false,
        //force_br_newlines: true,
        //forced_root_block: '',
        remove_trailing_nbsp: true,
        remove_linebreaks: false,
        dialog_type: 'modal',
        convert_urls:false,
        maxlength: 5000              
    });
}

function processCallback(data) {
    if(data.exceptionOccured) {
        $.modal.close();
        $("#ModalWrapper").modal({ overlay : 90 });
        $("#ModalWrapper").load("/Error/ServiceFailure?isAjax=true");
    }
    
    if(data.requireLogin) {
        alert("must login");
    }
}

 function parseScore(score, rate)
    {
          var rtnValue = rate;
        if (!isNaN(parseFloat(score)))
        {
            rtnValue = parseFloat(score) + parseFloat(rate);
        }
        
        if (isNaN(rtnValue) || rtnValue == 0)
            return "0";
        else
            return rtnValue;
    }
    
    function loadRating()
    {
     $(".agree").click(function() {
            // Disable the agree/disagree buttons for this section
            $(this).attr("disabled","disabled");
            $(this).parent().find(".disagree").attr("disabled","disabled");

            var rating = $(this).parent().find("#Rating");
            var score = $(this).parent().find(".score");
            var ratingId = $(this).parent().find("#RatingId").val();
            var itemId = $(this).parent().find("#ItemId").val();
            var itemType = $(this).parent().find("#ItemType").val();
            var ratingValue = $(this).parent().find("#AgreeValue").val();
            var rateAction = "Agree";
            var currentItem = this;
            
            if(!$(this).is(".rateUp")) {
                    $.post("/Rating/AsyncRate/", {isAjax:  true,
                                                      ratingId: ratingId, 
                                                      itemId:  itemId,
                                                      itemType: itemType, 
                                                      rateAction: rateAction},
                                                       function(data){ 
                                                                        processCallback(data);
                                                                        if (data.success){  
                                                                            $(currentItem).addClass("rateUp");
                                                                            $(currentItem).parent().find(".disagree").removeClass("rateDown");
                                                                            $(score).html(parseScore($(score).html(), ratingValue - $(rating).val()));
                                                                            $(rating).val(ratingValue);
                                                                            $(currentItem).parent().find("#RatingId").val(data.ratingId);
                                                                            $(currentItem).removeAttr("disabled");
                                                                            $(currentItem).parent().find(".disagree").removeAttr("disabled");
                                                                            }                
                                                                     }, "json");
                    }
                    else
                    {
                        $(currentItem).removeAttr("disabled");
                        $(currentItem).parent().find(".disagree").removeAttr("disabled");
                    }
                });
                                                
        $(".disagree").click(function() {
            // Disable the agree/disagree buttons for this section
            $(this).attr("disabled","disabled");
            $(this).parent().find(".agree").attr("disabled","disabled");

           var rating = $(this).parent().find("#Rating");
           var score = $(this).parent().find(".score");
           var itemId = $(this).parent().find("#ItemId").val();
           var itemType = $(this).parent().find("#ItemType").val();
           var ratingId = $(this).parent().find("#RatingId").val();
           var ratingValue = $(this).parent().find("#DisagreeValue").val();
           var rateAction = "Disagree";
           var currentItem = this;
             
             if(!$(currentItem).is(".rateDown")) {
                    $.post("/Rating/AsyncRate/", {isAjax:  true, 
                                                      ratingId: ratingId, 
                                                      itemId:  itemId,
                                                      itemType: itemType, 
                                                      rateAction: rateAction},
                                                       function(data){ 
                                                                        processCallback(data);
                                                                        if (data.success){  
                                                                            $(currentItem).addClass("rateDown");
                                                                            $(currentItem).parent().find(".agree").removeClass("rateUp");
                                                                            $(score).html(parseScore($(score).html(), ratingValue - $(rating).val()));
                                                                            $(rating).val(ratingValue);
                                                                            $(currentItem).parent().find("#RatingId").val(data.ratingId);
                                                                            $(currentItem).removeAttr("disabled");
                                                                            $(currentItem).parent().find(".agree").removeAttr("disabled");
                                                                            }                
                                                                     }, "json");
            }   
            else
            {
                $(currentItem).removeAttr("disabled");
                $(currentItem).parent().find(".agree").removeAttr("disabled");
            }
        });
        
   
    
    }
    
