$(document).ready(function() {
    GlobalValidation.init();

    $('.boostajaxupload').each(function() {
        var callback = $(this).attr("callback");
        var id = $(this).attr("id");
        $(this).attr("id", "upload" + id);

        var htm = "<input type=hidden id='" + id + "' name='" + id + "' onchange='" + callback + "(this);' />";
        htm += "<iframe src='/PartialView/BoostFileUpload' id='frm" + id + "' style='height:30px;width:420px;border:none;' frameBorder=0 scrolling='no'></iframe>";
        $(this).html(htm);
        var myFrame = $('#frm' + id);
        myFrame.load(function() {
            if ($(this).contents().find("#returnurl").val() != "") {
                var url = $(this).contents().find("#returnurl").val();
                $("#" + id).val(url);
                $("#" + id).change();
            }
            $(this).contents().find("#parentId").val(id);
            $(this).contents().find("#txtFile").change(function() {
                if ($(this).val() != "") {
                    try {
                        var splitName = this.value.split(".");
                        var ext = splitName[splitName.length - 1];
                        var ValidFile = true;
                        switch (ext.toLowerCase()) {
                            case 'jpg':
                                break;
                            case 'gif':
                                break;
                            case 'jpeg':
                                break;
                            case 'bmp':
                                break;
                            case 'png':
                                break;
                            default:
                                ValidFile = false;
                                alert('Invalid file name or type, Please upload JPG, GIF, JPEG or PNG files.');
                                $(this).val('');
                                break;
                        }
                        if (ValidFile)
                            myFrame.contents().find("#frmUploadFile").submit();
                    } catch (e) { }
                }
            });

            $(this).contents().find("#lnkFileName").click(function() {
                $("#" + id).val("");
                $("#" + id).change();
                return false;
            });
        });
    });
});
//Extending javascript string object.
String.prototype.startsWith = function(str)
{return (this.match("^"+str)==str)}

String.prototype.endsWith = function(str)
{return (this.match(str+"$")==str)}

timedRefresh = function(timeoutPeriod) {
setTimeout("location.reload(true);", timeoutPeriod);
}

//Navigation auto selection
var BoostNavigation = function() {
    var _linkSelected = false;
    var mainLink = "";
    var selectedLink = "";

    return {
        init: function() {
            if (!_linkSelected)
                this.selectLink(window.location.href);

            var oSubLinks = $("div.subnav a");
            oSubLinks.each(function() {
                var id = this.id;
                $("#" + this.id).parent().hover(function() { BoostNavigation.showSubLink(id); });
            });

            var oMainLinks = $("div ul[id=ulMainNav] a");
            oMainLinks.each(function() {
                var hrf = this.href;
                $("#" + this.id).parent().hover(function() { BoostNavigation.showLink(hrf); });
            });

            $("#topMenuNavigation").mouseleave(function() {
                BoostNavigation.selectLink(selectedLink);
            });
        },
        selectLink: function(pLocation) {
            selectedLink = pLocation;
            this.mainLink = pLocation;
            this.showLink(pLocation);
        },
        showLink: function(pLocation) {
            this.hideLink(this.mainLink);
            var oCandidates = $("div.subnav a");
            oCandidates.each(function() {
                if (this.href.toUpperCase().endsWith(pLocation.toUpperCase())) {
                    $(this).addClass("active");
                    $(this).parent().parent().parent().css("display", "block");
                    $("#" + $(this).attr("rel")).addClass("active");
                    _linkSelected = true;
                    if (this.id == "subTabContestHistory") { $(this).show(); }
                }
                else {
                    $(this).removeClass("active");
                    if (this.id == "subTabContestHistory") { $(this).hide(); }
                }
            });
        },
        hideLink: function(pLocation) {
            var oCandidates = $("div.subnav a");
            oCandidates.each(function() {
                $(this).removeClass("active");
                $(this).parent().parent().parent().css("display", "none");
                $("#" + $(this).attr("rel")).removeClass("active");
                _linkSelected = true;
                if (this.id == "subTabContestHistory") { $(this).show(); }
            });
        },
        showSubLink: function(pLocation) {
            $("#" + $("#" + pLocation).parent() + "[rel]").removeClass("active");
            $("#" + pLocation).addClass("active");
        }

    };
} ();


//Account Left Navigation auto selection
var AccountLeftNavigation = function() {
    var _linkSelected = false;

    return {
        init: function() {
            if (!_linkSelected)
                this.selectLink(window.location.href);
        },

        selectLink: function(pLocation) {
            var oCandidates = $("ul.nav a");
            oCandidates.each(function() {
                if ((!this.href.toUpperCase().endsWith("#")) && this.href.toUpperCase().endsWith(pLocation.toUpperCase())) {
                    $(this).addClass("active");
                    _linkSelected = true;
                }
                else {
                    $(this).removeClass("active");
                }
            });
        }
    };
} ();

var FeedBackWidget = {
    showWidget: function(){
        $("#fdbk_tab").click();
    }    
};
	
$(function(){
try {
    BoostNavigation.init(); 
    AccountLeftNavigation.init();
}catch(e) {}
});



SoftPopupStatic = function(){
	var currentPopup;
	
	return {
		setCurrentPopup: function(pPopup){		    
		        currentPopup=pPopup; 
        },
		
		hide: function(){
			currentPopup.hide();
		}	
	};
}();

BoostModalBox = {
    showPopupModal: function(modalid, height, width) {
        var html = '<div id="' + modalid + '_Overlay" class="boostmodalboxoverlay"></div>';
        if ($("#" + modalid).length == 0) {
            html += '<div id="' + modalid + '" class="boostmodalboxcontent"></div>';
        } else {
            $("#" + modalid).removeClass("nodisplay");
            $("#" + modalid).removeClass("boostmodalboxcontent");
            $("#" + modalid).addClass("boostmodalboxcontent");
            $("#" + modalid).addClass("round5");
        }
        if ($("#" + modalid).css("padding") == "") {
            $("#" + modalid).css("padding", "10px");
            width += 20;
            height += 20;
        }
        $('body').append(html);
        $("#" + modalid).css("height", height + "px");
        $("#" + modalid).css("width", width + "px");
        var top = parseInt($(window).height() - height) / 2;
        $("#" + modalid).css("top", top + "px");
        var left = parseInt($(window).width() - width) / 2;
        $("#" + modalid).css("left", left + "px");
        $("#" + modalid + "_Overlay").css("width", $(window).width());
        $("#" + modalid + "_Overlay").css("height", $(window).height());
    },
    remove: function(modalid, onlyhide) {
        if (onlyhide == undefined)
            onlyhide = false;
        $("#" + modalid + "_Overlay").remove();
        if (onlyhide)
            $("#" + modalid).addClass("nodisplay");
        else
            $("#" + modalid).remove();
    },
    showMessage: function(message, title, height, width) {
        var modalid = "alertbox";
        var html = '<div id="' + modalid + '_Overlay" class="boostmodalboxoverlay"></div>';
        html += '<div id="' + modalid + '" class="boostmodalboxcontent in-modal" style="border:solid 2px #d9d9d9; padding:10px;">';
        //content += '<div class="signin" style="float:right; width:auto;"><a href="#" class="close" id="lnkClose" onclick="BoostModalBox.remove(\'' + modalid + '\');">close</a></div>';
        html += '<p class="title" style="text-align:left;">' + title + '</p><hr/><br/>' + message;
        html += '<br/><br/><div align="center"><a href="javascript:" onclick="BoostModalBox.remove(\'' + modalid + '\');" class="mOrange-btn"> OK </a></div></div>';
        $('body').append(html);
        $("#" + modalid).css("height", height + "px");
        $("#" + modalid).css("width", width + "px");
        var top = parseInt($(window).height() - height) / 2;
        $("#" + modalid).css("top", top + "px");
        var left = parseInt($(window).width() - width) / 2;
        $("#" + modalid).css("left", left + "px");
        $("#" + modalid + "_Overlay").css("width", $(window).width());
        $("#" + modalid + "_Overlay").css("height", $(window).height());
    }
}

ContestGuidelinesModal = {
    AdGroupId: 0,
    displayBoxId: '',
    showFromId: function(adGroupId) {
        this.adGroupId = adGroupId;
        if (this.adGroupId > 0) {
            $.post("/Writer/GetContestGuideline", {
                AdGroupId: adGroupId
            },
			   function(data) { ContestGuidelinesModal.showFromId_callback(data); });
        }
    },

    showFromId_callback: function(res) {
        if (res != null) {
            return;
        }
        return;
    },

    show: function(divId, callbackfunction) {
        var divHTML = $("#" + divId).html();
        var acceptButton = "<div class='cl'>&nbsp;</div><div align=center><a href='javascript:' onclick='ContestGuidelinesModal.hide(); " + callbackfunction + "' class='orange-button' style='float:none; padding:4px;'>I have read Guidelines</a></div>";
        var html = '<div id="' + divId + '_guidelines" style="color:#666;"><p style="color:#666; font-size: 22px; line-height: 26px; font-weight:bold;">Contest Guidelines</p><hr/><div style="overflow:auto;margin-bottom:10px;" id="divGuidelines">' + divHTML + '</div>' + acceptButton + '</div>';
        $('body').append(html);
        var height = $("#" + divId).height() + 100;
        var width = $("#" + divId).width();
        $("#divGuidelines").css("height", (height - 50) + "px");
        $("#divGuidelines").css("width", (width + 20) + "px");
        ContestGuidelinesModal.displayBoxId = divId + "_guidelines";
        BoostModalBox.showPopupModal(divId + "_guidelines", height, width);
    },

    hide: function(divId) {
        if (divId == undefined)
            divId = ContestGuidelinesModal.displayBoxId;
        BoostModalBox.remove(divId);
    }
}

SpellChecker = function(){};
SpellChecker.prototype = {
    serviceUrl: '/WebService/GetCorrections',
    inputElement: null,
    originalText: '',
    words: [],
    corrections: [],
    ignoreList: [],
    callback: null,
    correctionWindow: '<div class="overlaymodal" id="spellingModal">\
	            <div class="in-modal">\
					<div class="signin">\
						<a id="lnkCloseCreateAd" class="close" href="#">close</a>\
					</div>\
					<div>\
					<h1>Spell Check</h1>\
					<br/>\
					<strong>Not in Dictionary</strong>\
					<div id="divInputText" style="border: 1px solid ; width: 400px;">\
					</div>\
					<br/>\
					<strong id="labelSuggestion">Suggestions</strong>\
					<div>\
					<select id="selSuggestion" size="5" style="width:400px;">\
						\
					</select>\
					</div>\
					<br>\
					<input style="margin-right:10px;" type="button" id="btnReplace" value="Replace">\
					<input type="button" style="margin-right:20px;" id="btnIgnore" value="Ignore">\
					<div style="float:right;margin-right:40px">\
					<a href="javascript:void(0)" class="close">Cancel</a>\
					</div>\
					</div>\
					</div>\
	            </div>',

    checkSpelling: function(pInputElement, pCallBack) {
        var self = this;
        this.callback = pCallBack;
        if (!pInputElement)
            return;

        if (pInputElement.jquery)
            if (pInputElement.length > 0)
            this.inputElement = pInputElement[0];
        else { return; }
        else
            this.inputElement = pInputElement;


        if (this.inputElement != null) {
            this.originalText = this.inputElement.value;
            this.words = this.inputElement.value.split(' ');
        }

        //Get corrections if any
        $.post(this.serviceUrl, { Input: self.inputElement.value }, function(data) {
            //get words and corrections
            self.corrections = eval(data);
            self.words = self.inputElement.value.split(' ');
            if (self.corrections.length == 0)
                pCallBack(true);
            else
                self.runCorrectionUI();
        });
    },


    runCorrectionUI: function() {
        if (this.corrections != null && this.corrections.length > 0) {
            var self = this;
            //Add the spell correction markup
            existingModal = $('#spellingModal');
            if (existingModal.length > 0)
                existingModal.remove();

            BoostModalBox.showPopupModal("spellingModal", 300, 480);
            $("#spellingModal").append(this.correctionWindow);
            //$('body').append(this.correctionWindow);

            //Open the modal
            //var url = "#TB_inline?height=300&width=480&inlineId=spellingModal&modal=true";
            //tb_show("SpellChecking", url);

            //Attach events
            $('#spellingModal a.close').click(function() {
                self.cancelCorrection();
            });

            $('#btnReplace').click(function() {
                self.replace();
            });

            $('#btnIgnore').click(function() {
                if (self.corrections != null && self.corrections.length > 0) {
                    var currentWrongWord = self.originalText.slice(self.corrections[0].WordOffset, self.corrections[0].WordLength + self.corrections[0].WordOffset);
                    self.ignoreList.push(currentWrongWord);
                }
                self.goNext();
            });

            this.setUI();
        }
    },

    replace: function() {
        if (this.corrections != null && this.corrections.length > 0) {
            var currentCorrection = this.corrections[0];
            var oldWord = this.originalText.slice(currentCorrection.WordOffset, currentCorrection.WordLength + currentCorrection.WordOffset);
            var newWord = $('#selSuggestion').val();
            if (newWord != null && newWord.length > 0)
                for (i = 0; i < this.words.length; i++)
                if (this.words[i] == oldWord) {
                this.words[i] = newWord;
                break;
            }
            this.goNext();
        } else
            this.correctionSuccess();
    },

    goNext: function() {
        if (this.corrections != null) {
            if (this.corrections.length < 2) {
                this.corrections = [];
                this.correctionSuccess();
            }
            else {
                this.corrections.shift();
                this.setUI();
            }
        } else this.callback(true);
    },

    setUI: function() {
        if (this.corrections != null && this.corrections.length > 0) {
            var suggestioncount = 0;
            //Get array of corrections
            var currentCorrection = this.corrections[0];
            if (currentCorrection.Suggestions.length > 0) {
                for (var i = 0; i < currentCorrection.Suggestions.length; i++) {
                    suggestioncount += (currentCorrection.Suggestions[i] != undefined && currentCorrection.Suggestions[i] != "" ? 1 : 0);
                }
            }

            //Set text with word highlight
            inCorrectWord = this.originalText.slice(currentCorrection.WordOffset, currentCorrection.WordLength + currentCorrection.WordOffset)
            var highlightedText = '';
            var foundIncorrectWord = false;
            for (var i = 0; i < this.words.length; i++) {
                if (this.words[i] == inCorrectWord && !foundIncorrectWord) {
                    foundIncorrectWord = true;
                    highlightedText += "<span style='color:red;'>" + this.words[i] + "</span> ";
                }
                else
                    highlightedText += this.words[i] + ' ';
            }

            var foundInIgnoreList = false;
            for (var i = 0; i < this.ignoreList.length; i++) {
                if (this.ignoreList[i] == inCorrectWord)
                    foundInIgnoreList = true;
            }


            //if the word to be corrected wasn't found, or already ignored
            if (!foundIncorrectWord || foundInIgnoreList) {
                this.goNext();
                return;
            }

            $('#divInputText').html(highlightedText);

            //show suggestions
            var options = ''
            if (currentCorrection.Suggestions.length > 0 && suggestioncount > 0) {
                for (var i = 0; i < currentCorrection.Suggestions.length; i++) {
                    if (currentCorrection.Suggestions[i] != undefined)
                        options += '<option value="' + currentCorrection.Suggestions[i] + '">' + currentCorrection.Suggestions[i] + '</option>';
                }
                $('#selSuggestion').html(options);
                $('#btnReplace').removeClass("nodisplay");
                $('#labelSuggestion').removeClass("nodisplay");
                $('#selSuggestion').children()[0].selected = 'selected';
            } else {
                $('#selSuggestion').html('<option value="NoSuggestion">No Suggestions Found</option>');
                $('#btnReplace').addClass("nodisplay");
                $('#labelSuggestion').addClass("nodisplay");
                $('#selSuggestion').children()[0].selected = 'selected';
            }
            //            } else {
            //                this.correctionSuccess();
            //            }
        }
    },

    cancelCorrection: function() {
        //tb_remove();
        BoostModalBox.remove("spellingModal");
        if (this.callback)
            this.callback(false);
    },

    correctionSuccess: function() {
        if (this.words != null) {
            resultText = '';
            for (i = 0; i < this.words.length; i++) {
                resultText += this.words[i] + ' ';
            }
            $(this.inputElement).val($.trim(resultText));
        }

        //tb_remove();
        BoostModalBox.remove("spellingModal");
        if (this.callback)
            this.callback(true);
    }

}

/* Function for Signup.Master */
var HeaderSteps = {
    StepsHover: function(stepID) {
        switch(stepID)
        {
            case "tdsStepOne":
                $("#tdsStepOne").addClass("tdfocuson");
                $("#tdsStepOne").removeClass("tdfocusoff");
                $("#lblStepOne").removeClass("nodisplay");
                $("#imgStepOne").attr("src","/content/images/1_active.png");
                
                $("#tdsStepTwo").addClass("tdfocusoff");
                $("#tdsStepTwo").removeClass("tdfocuson");
                $("#lblStepTwo").addClass("nodisplay");
                $("#imgStepTwo").attr("src","/content/images/2_blue.png");

                $("#tdsStepThree").addClass("tdfocusoff");
                $("#tdsStepThree").removeClass("tdfocuson");
                $("#lblStepThree").addClass("nodisplay");
                $("#imgStepThree").attr("src","/content/images/3_blue.png");
                break;
            case "tdsStepTwo":
                $("#tdsStepOne").addClass("tdfocusoff");
                $("#tdsStepOne").removeClass("tdfocuson");
                $("#lblStepOne").addClass("nodisplay");
                $("#imgStepOne").attr("src","/content/images/1_green.png");
                
                $("#tdsStepTwo").addClass("tdfocuson");
                $("#tdsStepTwo").removeClass("tdfocusoff");
                $("#lblStepTwo").removeClass("nodisplay");
                $("#imgStepTwo").attr("src","/content/images/2_active.png");

                $("#tdsStepThree").addClass("tdfocusoff");
                $("#tdsStepThree").removeClass("tdfocuson");
                $("#lblStepThree").addClass("nodisplay"); 
                $("#imgStepThree").attr("src","/content/images/3_blue.png");
                break;
            case "tdsStepThree":
                $("#tdsStepOne").addClass("tdfocusoff");
                $("#tdsStepOne").removeClass("tdfocuson");
                $("#lblStepOne").addClass("nodisplay");
                $("#imgStepOne").attr("src","/content/images/1_green.png");
                
                $("#tdsStepTwo").addClass("tdfocusoff");
                $("#tdsStepTwo").removeClass("tdfocuson");
                $("#lblStepTwo").addClass("nodisplay");
                $("#imgStepTwo").attr("src","/content/images/2_green.png");

                $("#tdsStepThree").addClass("tdfocuson");
                $("#tdsStepThree").removeClass("tdfocusoff");
                $("#lblStepThree").removeClass("nodisplay");
                $("#imgStepThree").attr("src","/content/images/3_active.png");
                break;
        }
    }
};
/* Function for Signup.Master */

var BoostSearch = 
{
    Search: function()
    {
        if($("#boostsearchbox").val() != "" && $("#boostsearchbox").val() != "Search BoostCTR")
        {
            window.location.href = "/company/publiccontest/" + $("#boostsearchbox").val();
        }
    }
};

var HideDisplayNotes = {
    noteDivId: '',
    clickDisplayNotes: function(cookiesname, messageDv, displayvalue) {
        if (displayvalue == undefined)
            displayvalue = "false";
        HideDisplayNotes.noteDivId = messageDv;
        $.post("/Advertiser/CookiesDisplayNotesHide",
                                        { displayNotesStatus: displayvalue, CookiesName: cookiesname },
                                        function(data) { HideDisplayNotes.clickContestDisplayNotes_callback(data); }, "json");
    },

    clickContestDisplayNotes_callback: function(response) {
        if (HideDisplayNotes.noteDivId != "") {
            $("#" + HideDisplayNotes.noteDivId).addClass("nodisplay");
        }
    }
}

var UserDashboardAlerts = {
    noteDivId: '',
    MessageIDs: new Array(),
    addMessageId: function(messageId) {
        UserDashboardAlerts.MessageIDs[UserDashboardAlerts.MessageIDs.length] = messageId;
    },

    hideAlert: function(messageId) {
        UserDashboardAlerts.noteDivId = "divUserAlerts";
        $.post("/MessageBoard/CloseUserMessageAlert",
                                        { UserMessageID: UserDashboardAlerts.MessageIDs },
                                        function(data) { UserDashboardAlerts.hideAlert_callback(data); }, "json");
    },

    hideAlert_callback: function(response) {
        if (UserDashboardAlerts.noteDivId != "") {
            $("#" + HideDisplayNotes.noteDivId).hide(300);
            $("#" + HideDisplayNotes.noteDivId).addClass("nodisplay");
        }
    }
}

var GlobalValidation = {
    IsValidated: false,
    init: function() {
        $("input[vrequired=true]").each(function() {
            $(this).blur(function() {
                ($.trim($(this).val()) == "" ? $(this).addClass(($(this).attr("errorclass") != null ? $(this).attr("errorclass") : "errorfield")) : $(this).removeClass(($(this).attr("errorclass") != null ? $(this).attr("errorclass") : "errorfield")));
                $(this).attr("vvalidated", ($.trim($(this).val()) == "" ? false : true));
            });
        });
    },

    IsValidated: function() {
        $("input").each(function() {
            if ($(this).attr("vvalidated") != null) {
                if ($(this).attr("vvalidated") == "false") {
                    GlobalValidation.IsValidated = false;
                    return;
                } else {
                    GlobalValidation.IsValidated = true;
                }
            }
        });
    }
}

var SupportQuestion = {
    SendQuestion: function(subject) {
        ProcessOverlay.show("TB_ajaxContent");
        if ($("#txtQuestionMessage").val() != "") {
            $.post("/Advertiser/SendQuestionToSupport",
                {
                    Subject: subject,
                    Question: $("#txtQuestionMessage").val()
                },
                function(data) { SupportQuestion.SendQuestion_callback(data); }, "json");
        }
        else {
            alert("Please enter a question.");
            ProcessOverlay.hide("TB_ajaxContent");
        }
    },

    SendQuestion_callback: function(resp) {
        if (resp == "Success") {
            alert("Question sent successfully.");
        } else {
            alert(resp);
        }
        ProcessOverlay.hide("TB_ajaxContent");
        tb_remove();
    }
}
