"use strict";
/*globals $, jQuery, window, document, pageTracker */
var DUMAS = (function () {

    var dumas = {},

    /**********************************************************************
     * Minimal JSP / JS / Singleton synch code.  Separate if it gets big
     **********************************************************************/
    initCallbacks = [],
    contextCallbacks = {},
    contextInitiliazed;

    function initContext(context) {
        if (contextCallbacks[context] && contextCallbacks[context].length) {
            jQuery.each(contextCallbacks[context], function () {
                this(dumas[context]);
            });
        }
    }

    function initAllContext() {

        jQuery.each(initCallbacks, function () {
            this();
        });

        jQuery.each(contextCallbacks, function (context) {
            initContext(context);
        });
        contextInitiliazed = true;
    }

    function newContextData(context, data) {
        if (context) {
            if (dumas[context]) {
                jQuery.extend(dumas[context], data);
            } else {
                dumas[context] = data;
            }
        } else {
            jQuery.extend(dumas, data);
        }

        if (contextInitiliazed) {
            initContext(context);
        }
    }

    function addInitCallback(callback) {
        initCallbacks.push(callback);
        return dumas;
    }

    function addContextCallback(context, callback) {
        var ctx = contextCallbacks[context];

        if (!ctx) {
            ctx = contextCallbacks[context] = [];
        }

        ctx.push(callback);

        if (contextInitiliazed) {
            callback(dumas[context]);
        }

        return dumas;
    }

    jQuery.extend(dumas, {
        init: addInitCallback,
        context: addContextCallback,

        // JSP calls below:
        _initAllContext: initAllContext,
        _ctxData: newContextData
    });


    /*************************************
     * String prototype extension
     *************************************/
    jQuery.extend(String.prototype, {

        constrain: function (len) {
            return this.length < len ? this : this.substring(0, len - 3) + '...';
        },
        trim: function () {
            return jQuery.trim(this);
        }
    });

    /*************************************
     * jQuery collection base extension
     *************************************/
    jQuery.fn.extend({
        serializeObj: function () {
            var val, build = [], self = this.get(0);

            for (val in self) {
                if (Object.hasOwnProperty.call(self, val)) {
                    build.push([val, '=', self[val], '&'].join(''));
                }
            }

            return build.join('');
        },
        setClass : function (test, classOne, classTwo) {
            this[test ? 'addClass' : 'removeClass'](classOne);
            return (classTwo) ? this[!test ? 'addClass' : 'removeClass'](classTwo) : this;
        },
        deserialize : function (attrName) {
            return jQuery.deserialize(this.attr(attrName || 'href'));
        },
        updateQueryString: function (callback, attrName) {
            return this.each(
                function () {
                    var jq = $(this),
                        href,
                        baseUrl,
                        params,
                        qsIndex;

                    attrName = attrName || 'href';

                    href = jq.attr(attrName);
					if (href) {
						qsIndex = href.indexOf('?');
						baseUrl = (qsIndex >= 0) ? href.substring(0, qsIndex + 1) : href;
						params = jQuery.deserialize(href);

						callback(params, jq, baseUrl);

						jq.attr(attrName, baseUrl + jQuery.param(params));
					}
                }
            );
        },
        setVisible: function (visible) {
            return this.css('visibility', visible ? 'visible' : 'hidden');
        }

    });


    /*************************************
     * jQuery object base extension
     *************************************/
    jQuery.extend({

        deserialize : function (url) {
            var result = {}, params, param, index, i;
            index = url.indexOf('?');
            if (index >= 0) {
                params = url.substring(index + 1).split('&');
                for (i = 0; i < params.length;) {
                    param = params[i].split('=');
                    result[param[0]] = param[1];
                    i = i + 1;
                }
            }
            return result;
        }
    });

	function disableDoubleSubmit() {
		var hasSubmitted = false, $el;
		$('.singleSubmit').each( function(){
			$el = $(this);
			$el.submit(function(){
				if (hasSubmitted) {
					return false;
				} else {
					hasSubmitted = true;
					$el.find('button, input[type=image]').attr('disabled', 'disabled');
					return true;
				}
			});
		});
	};


//todo break these out

    function initLoyaltyBox() {
        var  dalRight = DUMAS.loyalty ? DUMAS.loyalty.dalRight : false;
        if (dalRight) {
            $('#loyaltyDialog').jqm({
                ajax :	'/remote/loyalty.html',
                closeClass : 'jqmClose',
                overlay : 50,
                target : $('.fancyBoxContent'),
                toTop : 'true',
                onShow : function (h) {
                    h.w.css('top', DUMAS.scrollTop() + 40 + "px")
                        .css('left', (DUMAS.clientWidth() / 2) - (h.w.width() / 2) + "px")
                        .fadeIn('normal');
                }
            }).jqmShow();
        }
    }

	function redirect(val) {
		self.location = val;
	}

	function closeWindow() {
		if (isWMP()) {
			goBack();
		} else {
			self.close();
		}
	}

	function goBack() {
		history.back();
	}

	// *** popUp code
	// ***
	// don't pop up if its a wimp
	function isWMP(){
		return  location.hostname.substring(0, 3) === "wmp";
	}

	function setPopUp(params) {
		var defaults, options, windowSettings = '', props;
		defaults = {
			height: 620,
			width: 565,
			menubar: 0,
			resizable: 1,
			status: 0,
			scrollbars : 1,
			toolbar : 0
		};
		options = jQuery.extend(defaults, params);
		for (props in defaults) {
			if (defaults.hasOwnProperty) {
				windowSettings += props + "=" + defaults[props] + ",";
			}
		}
		windowSettings = windowSettings.substring(0, windowSettings.length - 1);
		return windowSettings;
	}
	function openWindow(url, name, params) {
		var settings = setPopUp(params);
		if (name === undefined) {
			name = '';
		}
		window.open(url, name, settings);
		return false;
	}
	function popUp(params, name, href) {
			return function (e) {
				if (!isWMP()) {
					href = href || e.target.href;
					openWindow(href, name, params);
					return false;
				}
			};
	}


	function initCommonClicks() {

		$('a.terms, a.genericPop').click(popUp());
		$('a.privacy').click(popUp({width: 765, height: 500}));
		$('a.closeWindow').click(closeWindow);
		$('a.goBack').click(goBack);
		ga_messaging('#phasedOfferMessage');

	}

	function ga_messaging(el) {
		$(el)
			.bind('click.googleEvents',
				function (){
					_gaq.push(['_trackEvent', 'Trial Event', 'Clicked on Phased Offer Account Page Link']);
					window.location.href = elem.attr('href');
					return false;
				});
	}



    $(function () {
		disableDoubleSubmit();
        initLoyaltyBox();
		initCommonClicks();
    });

    return dumas;
}());

/*
* gives inner module functions a specific global name to expose themselves to be unit-tested
*/
var QUnit = {};




//testing only



