ScholasticKidsRegistration = {

    assetsLoaded: false,
    stylesheets: ['kids_popup'],
    javascripts: ['kups_login', 'kups_registration', 'kups_password_recovery', 'kups_campaign', 'kups_schools'],

    overlay: jQuery('<div id="kids_registration_overlay" style="display: none"></div>'),
    container: jQuery('<div id="kids_registration_popup_container" style="display: none"></div>'),
    close: jQuery('<a class="kids_registration_close" href="#close"><img src="/ups/images/kids_popup/btn-close.png" alt="close" /></a>'),
    target: jQuery('<div class="kids_registration_target" id="kids_registration_target"></div>'),

    loadStyleSheets: function() {
        if (jQuery.browser.msie && jQuery.browser.version.substr(0,1) < 7) {
            this.stylesheets.push('ie');
        }
        jQuery.each(this.stylesheets, function(i) {
            if(jQuery.browser.msie) {
                document.createStyleSheet('/ups/stylesheets/' + ScholasticKidsRegistration.stylesheets[i] + '.css');
            } else {
                jQuery('<link rel="stylesheet" type="text/css" href="/ups/stylesheets/' + ScholasticKidsRegistration.stylesheets[i] + '.css" />').appendTo('head');
            }
        });
    },

    loadJavaScripts: function() {
        if(typeof swfobject == 'undefined') {
            this.javascripts.push('swfobject');
        }
        jQuery.each(this.javascripts, function(i, script) {
      document.writeln('<script src="/ups/javascripts/' + script + '.js" type="text/javascript"><\/script>');
        });
    },

    initialize: function() {
        if(!this.assetsLoaded) {
            this.loadStyleSheets();
            this.loadJavaScripts();
            this.assetsLoaded = true;
        }
        var _self = this;
        this.mainSuccessURL = ScholasticKidsRegistration.getUrlVars()["finalSuccessURL"];

        this.close.click(function(c) {
            c.preventDefault();
            if(_self.isRemembered()) {
                window.location.reload();
            } else {
                jQuery('body').css('overflow', 'auto');
                _self.overlay.remove();
                _self.overlay.add(_self.container).fadeOut('normal');
                _self.target.html('');
                _self.initialize();
            }
        });

        this.overlay.append(this.container);
        this.container.append(this.close).append(this.target);

        var containerHeight = 400;
        if(this.container.css('height') != 'auto') containerHeight = this.container.css('height').substring(0,3);
        var containerWidth = 600;
        if(this.container.css('width') != 'auto') containerWidth = this.container.css('width').substring(0,3);

        this.container.show().css({'top': Math.round(((jQuery(window).height() > window.innerHeight ? window.innerHeight : jQuery(window).height()) - containerHeight) / 2) + 'px',
                                   'left': Math.round((jQuery(window).width() - containerWidth) / 2) + 'px',
                                   'margin-top': 0,
                                   'margin-left': 0}).hide();

    },

    getCampaignCode: function(element) {
      var rel = this.getCampaignRel(element);
      return rel === "" ? null : rel.substring('kids_campaign_'.length);
    },

    getCampaignRel: function(element) {
        var campaign_rel = jQuery(element).attr('rel').match(/kids_campaign_[a-z0-9_-]+/);
        return campaign_rel == null ? "" : campaign_rel[0];
    },

    decideOnHref: function(href) {
        if(this.mainSuccessURL != null) {
            return this.mainSuccessURL;
        } else {
            var go_to = href[0] == "#" ? window.location.href : href;
            return go_to.split('#')[0];
        }
    },

    open: function(open_url, target_url, campaign_rel) {
        if(this.container.is(':visible')) {
            this.target.children().fadeOut('normal', function() {
                jQuery('body').remove('#kids_registration_overlay');
                ScholasticKidsRegistration.target.children().remove();
                ScholasticKidsRegistration.loadUrl(open_url, target_url, campaign_rel);
            });
        } else {
            jQuery('body').remove('#kids_registration_overlay');
            this.target.children().remove();
            this.overlay.add(this.container).fadeIn('normal',function(){
                ScholasticKidsRegistration.loadUrl(open_url, target_url, campaign_rel);
            });
        }
    },

    loadUrl: function(open_url, target_url, campaign_rel) {
        if(this.container.is('.kids_registration_loading')) { return; }
        jQuery('body').prepend(this.overlay);
        jQuery('body').css('overflow', 'hidden');
        this.container.addClass('kids_registration_loading');

        jQuery.ajax({ url: open_url,
                      dataType: (jQuery.browser.msie) ? "text" : "html",
                      data: {
                          'redirect_back_to_url' : target_url,
                          'campaign_rel' : campaign_rel
                      },
                      success: function(data) {
                          ScholasticKidsRegistration.container.removeClass('kids_registration_loading');
                          ScholasticKidsRegistration.target.html(data);
                          ScholasticKidsRegistration.recalculateFrameSize(function() {
                              ScholasticKidsRegistration.overlay.show();
                              ScholasticKidsRegistration.container.show();
                          }, 600, 400);
                      }});
    },

    ajaxSubmit: function(formElement) {
        jQuery.ajax({type: jQuery(formElement).attr('method'),
                     data: jQuery(formElement).serialize(),
                     url: jQuery(formElement).attr('action'),
                     async: false,
                     dataType: 'script'
                    });
    },

    isRemembered: function() {
        var sps_ud = ScholasticKidsRegistration.cookie('SPS_UD');

        return (sps_ud != null && sps_ud.length > 0)
    },

    recalculateFrameSize: function(callBackFunction, width, height, skipCheck) {
        this.overlay.height(jQuery(document).height());
        if(!skipCheck){
            if(this.target.outerWidth() > width) width = this.target.outerWidth();
            if(this.target.outerHeight() > height) height = this.target.outerHeight();
        }
        this.container.animate({'width': width,
                                'height': height,
                                'top': Math.round(((jQuery(window).height() > window.innerHeight ? window.innerHeight : jQuery(window).height()) - height - parseInt(this.container.css('padding-top'),10) - parseInt(this.container.css('padding-bottom'),10)) / 2) + 'px',
                                'left': Math.round((jQuery(window).width() - width - parseInt(this.container.css('padding-left'),10) - parseInt(this.container.css('padding-right'),10)) / 2) + 'px'},'normal', callBackFunction);
    },

    getUsernameNumber: function(words) {
        var number = jQuery.ajax({url: '/ups/kids/screenname', data: {username_word_1: words[0].toLowerCase(), username_word_2: words[1].toLowerCase()}, type: 'POST',async: false }).responseText;
        jQuery('#kids_registration_username_word_1').val(words[0].toLowerCase());
        jQuery('#kids_registration_username_word_2').val(words[1].toLowerCase());
        jQuery('#kids_registration_username_word_3').val(number);

        return number;
    },

    setUsername: function(username) {
        jQuery('#error_msg_step1').html('');
        jQuery('#error_msg_step1').hide();
    },

    getUrlVars: function() {
        var vars = {};
        var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
            vars[key] = value;
        });
        return vars;
    },

    cookie: function(name, value, options) {
        if (typeof value != 'undefined') {
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            // CAUTION: Needed to parenthesize options.path and options.domain
            // in the following expressions, otherwise they evaluate to undefined
            // in the packed version for some reason...
            var path = options.path ? '; path=' + (options.path) : '';
            var domain = options.domain ? '; domain=' + (options.domain) : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        } else {
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    },

    removeCookie: function(name, options) {
        if(name != null && (typeof name == 'string')) {
            options = options || {};

            if(!options.domain || (typeof options.domain != 'string')) {
                options.domain = '.scholastic.com';
            }

            var date = new Date();
            document.cookie = "" + name + "=1;path=/;domain=" + options.domain + ";expires=" + date.toGMTString() + ";" + ";";
        }
    }
}

ScholasticKidsRegistration.initialize();

