//The load event for the entire site
$(document).ready(function() {

    $('#flashbox a, #kelloggs-nav a').attr('target', '_blank');

    //Detect if the element id #sweepstakes is on the page
    //If the element has a length of 0 (not on the page) then call loadSWF
    //If not, then hide #flashbox 
    if ($('#sweepstakes').length == 0 && $('#sweeps-intro').length == 0) {
        loadSWF('MiniShell.swf', 'flashbox', '915', '560', '9.0.115.0');
    } else {
        $('#flashbox').addClass('hideFlash');
    }

    // Load sweepstakes landing page flash with a call to loadSWF
    if ($('#sweeps-intro').length == 1) {
        loadSWF('KLG_FMW_BTS_Site_837x544.swf', 'sweeps-intro', '915', '560', '9.0.115.0');
    }

    // Load sweepstakes closed landing page flash with a call to loadSWF
    if ($('#over').length == 1) {
        loadSWF('KLG_FMW_BTS_Site_837x544_2.swf', 'over', '915', '560', '9.0.115.0');
    }

    // Load sweepstakes background popup flash with a call to loadSWF
    if ($('#sweepstakes').length == 1) {

        loadSWF('KLG_FMW_BTS_Site_837x544_3.swf', 'sweepstakes-flash', '915', '560', '9.0.115.0');

        // Set the width for select (form dropdowns) elements via jq.ie-select-width.min.js plugin
        $('select').ieSelectWidth
        ({
            width: 234,
            containerClassName: 'select-container',
            overlayClassName: 'select-overlay'
        });
    }

    //Any Element with an Id of rules-link calls the colorbox function from jquery.colorbox-min.js
    //Important - dont change function name as this function is being accessed by some actionscript files.



    //Popup Object
    //initialize calls the colorbox function from jquery.colorbox.min.js
    //load adds a class to the colorbox and displays the legal copy
    //close removes the class and hides the legal copy
    var Popup = {
        initialize: function() {
            $.fn.colorbox({
                inline: true,
                href: '#all-popup-content',
                transition: 'none',
                speed: '0',
                width: '915px',
                height: '560px',
                opacity: '0.7',
                overlayClose: false,
                onLoad: function() { Popup.load() },
                onCleanup: function() { Popup.close() }
            });
            $('#popup-content').click(function() {
                Popup.setCookie("Sweeps", "popupCookie", 142);
            });
        },
        load: function() {
            loadSWF('popUpfla.swf', 'popup-content', '627', '390', '9.0.115.0');
            $('.intro-legal').show();
            $('#flashbox').replaceWith('<div id="placeholder-flash"></div>');
            $('#cboxContent').addClass('home');
            $('#cboxClose').addClass('pop-home');
            $('#cboxClose').addClass('google-track');
            $('#cboxClose').attr('rev', 'closed.x.clicked');
        },
        close: function() {
            $('.intro-legal').hide();
            $('#cboxClose').hide();
            $('#all-popup-content').hide();
            Popup.setCookie("Sweeps", "popupCookie", 142);
            window.location = window.location.protocol + '//' + window.location.host + '/';
        },
        setCookie: function(name, value, days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            } else {
                var expires = "";
            }
            document.cookie = name + "=" + value + expires + "; path=/";
        }
    };


    $('.rules-link').click(function(event) {
        event.preventDefault();
        $(this).colorbox({
            href: 'div#rules-content',
            inline: true,
            transition: 'none',
            speed: '0',
            width: '567px',
            height: '369px',
            opacity: '0.7',
            overlayClose: false,
            onLoad: function() {
                $('#cboxWrapper').removeClass('popup-link');
                $('#cboxWrapper').addClass('rules-link');
                $('#cboxContent').addClass('rules-link');
                $('#cboxClose').css('right', '2px');
                $('#cboxLoadedContent').addClass('rules-link');
                $('#all-popup-content').hide();
            },
            onCleanup: function() {
                $('.intro-legal').hide();
            },
            onClosed: function() {
                if ($('#all-popup-content').length == 1) {
                    $('#cboxWrapper').addClass('popup-link');
                    $('#cboxWrapper').removeClass('rules-link');
                    $('#cboxContent').removeClass('rules-link');
                    $('#cboxLoadedContent').removeClass('rules-link');
                    $('#all-popup-content').show();
                    $('#cboxClose').css('right', '131px');
                    $(Popup.initialize);
                }
            }
        });
    });
    
    
    

    //History Object
    //previous = the page where the user came from
    //initialize takes two parameters - path(the pathname to check for) and element(the element to attach the event to)
    //check function checks to see if previous is equal to path, if it is, back is called
    //back holds the click event for the element and redirect the user back to the previous page
    var History = {
        previous: document.referrer,
        initialize: function(path, element) {
            History.check(path, element);
        },
        check: function(path, element) {
            var targetPage = window.location.protocol + '//' + window.location.host + '/' + path + '/';
            if (History.previous && History.previous == targetPage) {
                History.back(element, targetPage);
            }
        },
        back: function(element, targetPage) {
            $(element).click(function(event) {
                event.preventDefault();
                window.location = targetPage;
            });
        }
    };

    //Initialize the History Object
    $(History.initialize('sweepstakesEntry2', 'a#enter-tab'));

    //Check if the pages pathname is equal to / (this means its the home page)
    //If it is, initialize the Popup object
    if ($('#popup-content').length == 1) {
        $(Popup.initialize);
    }

    //Call Get Resolution on the print page.
    if ($('#sweeps-print-container').length == 1) {
        getResolution();
    }

    //Clear the textarea #enter-resolution of its default value when the user clicks inside it for the first time.
    $('#enter-resolution').focus(function() {
        var textarea = $(this);
        var maxChar = 140;

        if (textarea.val() == 'Type your resolution here') {
            textarea.val('');
            $('.counter').html(maxChar + ' characters left!');

            //Event for the keypress inside the textbox
            $(this).keyup(function(event) {
                var length = textarea.val().length;
                //If the user presses enter, don't count it as a character or part of the textarea's val.
                if (event.keyCode == 13) {
                    var minusEnter = textarea.val().substring(0, length - 1);
                    textarea.val(minusEnter);
                } else {
                    //if the lenght of the textarea string is greater than the max Characters alowed,
                    //remove anything else that is typed.
                    if (length >= maxChar) {
                        var textareaValue = textarea.val().substring(0, maxChar);
                        textarea.val(textareaValue);
                        $('.counter').html('You have no more characters left!');
                    } else {
                        $('.counter').html(maxChar - length + ' characters left!');
                    }
                }
            });
        }
    });

    //Validation Object for handling the form on sweepstakesEntry page
    //Success method calls the function StoreResolution
    //Fail method appends error text to an empty div and colors the appropriate fields
    var Validation = {
        initialize: function() {
            var textboxVal = $('#enter-resolution').val();
            var selectVal = $('#select-resolution').val();

            if ($('input[name=agreement]').attr('checked') == false) {
                var message = 'You must agree to the official rules before you move on to the next step.';
                Validation.fail(message, true);
            } else if (textboxVal == '' || textboxVal == 'Type your resolution here') {
                Validation.fail('textbox fail');
                if (selectVal == '' || selectVal == 'Select one of our predefined resolutions...') {
                    var message = 'Please enter a resolution into the text box or choose from one of our options from the drop down list.';
                    Validation.fail(message, false);
                } else {
                    $('.error-message').html('');
                    Validation.success(selectVal);
                }
            } else {
                $('.error-message').html('');
                Validation.success(textboxVal);
            }
        },
        success: function(resolution) {
            profanityCheck(resolution);
            //storeResolution(resolution);
        },
        fail: function(text, agree) {
            $('.error-message').html(text);
            if (agree == false) {
                $('#enter-resolution').addClass('highlighted');
                $('#select-resolution').addClass('highlighted');
            } else if (agree == true) {
                $('#enter-resolution').removeClass('highlighted');
                $('#select-resolution').removeClass('highlighted');
            }
        }
    }

    //Change the state of the next button from inactive to active if the user click the agreement checkbox.
    $('input[name=agreement]').click(function() {
        $('#toStep2').removeClass('inactive');
    });

    //Initialize the validation object on the click event
    $('#toStep2').click(function(event) {
        event.preventDefault();
        Validation.initialize();
    });

});
//End Page Load Function


//popup
var win = null;
function NewWindow(mypage,myname,w,h,scroll){
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	settings =
	'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable'
	win = window.open(mypage,myname,settings)
}

//close iframe
function closeiframe(){
    parent.document.getElementById("frame1").style.display="none"
}

//Function that loads the main swf object for the site
function loadSWF(swf, elementId, width, height, version) {
    var flashvars = {};
    flashvars.sweeps = '/sweepstakesEntry/';
    flashvars.resolutions = '/resolutions/';
    var params = { wmode: 'transparent' };
    var attributes = {};
    var flashobject = '/_res/swf/' + swf;
    var expressinstall = '/_res/swf/expressInstall.swf';

    swfobject.embedSWF(flashobject, elementId, width, height, version, expressinstall, flashvars, params, attributes);
}


//Stores the Resolution text in session, need this so that resolution 
//entered can be retrieved at a later step like download & print
function storeResolution(resolutionText) {
    var updateUrl = window.location.protocol + '//' + window.location.host + '/';
    updateUrl += 'StoreResolution?ResolutionText=' + resolutionText;

    $.ajax({
        type: 'GET',
        cache: false,
        contentType: 'JSON',
        url: updateUrl,
        complete: function() {
            var targetPage = window.location.protocol + '//' + window.location.host + '/sweepstakesEntry2';
            window.location = targetPage;
        }
    });
}


//Checks the Resolution for profanity 
function profanityCheck(resolutionText) {
    var updateUrl = window.location.protocol + '//' + window.location.host + '/';
    updateUrl += 'ProfanityFilterCheck?ResolutionText=' + resolutionText;

    $.getJSON(updateUrl, function(data) {
        if (data.ReturnCode == 6) {
            $('.error-message').html('Oops! Please try writing your resolution a little differently.');
        } else if (data.ReturnCode == 4) {
            $('.error-message').html('Oops! The system is down. Please try again later.');
        } else if (data.ReturnCode == 1) {
            storeResolution(resolutionText);
        }
    });
}



//Retrieves the Stored resolution from the session with an ajax json call and injects the 
// result string into the print page
function getResolution() {

    var getUrl = window.location.protocol + '//' + window.location.host + '/GetResolution/';
    $.getJSON(getUrl, function(data) {
        var result = data.ResultStr;
        var resolution = result.substring(0, 1).toLowerCase() + result.substring(1);
        $('.jsonResData').html(resolution);
    });
}

//Rules Popup function for Flash
function RulesPopup() {
    $.fn.colorbox({
        href: 'div#rules-content',
        inline: true,
        transition: 'none',
        speed: '0',
        width: '567px',
        height: '369px',
        opacity: '0.7',
        overlayClose: false,
        onLoad: function() {
            $('#cboxWrapper').removeClass('popup-link');
            $('#cboxWrapper').addClass('rules-link');
            $('#cboxContent').addClass('rules-link');
            $('#cboxClose').css('right', '2px');
            $('#cboxLoadedContent').addClass('rules-link');
            $('#all-popup-content').hide();
        },
        onCleanup: function() {
            $('.intro-legal').hide();
        },
        onClosed: function() {
            if ($('#all-popup-content').length == 1) {
                $('#cboxWrapper').addClass('popup-link');
                $('#cboxWrapper').removeClass('rules-link');
                $('#cboxContent').removeClass('rules-link');
                $('#cboxLoadedContent').removeClass('rules-link');
                $('#all-popup-content').show();
                $('#cboxClose').css('right', '131px');
                $(Popup.initialize);
            }
        }
    });
};
