"use strict";

/*globals $, jQuery, window, document, DUMAS, navigator, self, screen, pageTracker */

/* EXTEND DUMAS WITH OLD BAD FUNCTIONS */

// jmarnell's old ass unneeded crap and some dom stuff
jQuery.extend(DUMAS, {

	/****
	* takes a url (for example from an anchor tags href attribute) calls jQuery.ajax with it and whatever other options are defined
	******/
	ajax: function (options) {
		var fullUrl, qsIndex = options.url.indexOf('?');
		if (qsIndex >= 0) {
			fullUrl = options.url;
			options.url = fullUrl.substring(0, qsIndex);
			options.data = fullUrl.substring(qsIndex + 1) + "&js=yes";
		} else {
			options.data = '';
		}

		return $.ajax(options);
	},

	loadCss: function (href, condition) {
		if (!condition || DUMAS.browser(condition)) {
			var oLink, i, head = document.getElementsByTagName('head')[0];
			for (i = 0; i < head.childNodes.length; i = i + 1) {
				if (head.childNodes[i].nodeName.toLowerCase() === 'link' && head.childNodes[i].href.indexOf(href) >= 0) {
					return;
				}
			}

			oLink = document.createElement("link");
			oLink.href = href;
			oLink.rel = "stylesheet";
			oLink.type = "text/css";
			head.appendChild(oLink);
		}
	},

	loadJs: function (src) {
		var i, oLink, head = document.getElementsByTagName('head')[0];
		for (i = 0; i < head.childNodes.length; i = i + 1) {
			if (head.childNodes[i].nodeName.toLowerCase() === 'script' && head.childNodes[i].src.indexOf(src) >= 0) {
				return;
			}
		}

		oLink = document.createElement("script");
		oLink.src = src;
		oLink.type = "text/javascript";
		head.appendChild(oLink);
	},

	param: function (name) {
		var results = new RegExp("[\\?&]" + name + "=([^&#]*)").exec(window.location.href);
		return results === null ? null : results[1];
	},

	browser: function (browserString) {
		return (browserString === 'ie'      && $.browser.msie) ||
			   (browserString === 'mozilla' && $.browser.mozilla) ||
			   (browserString === 'safari'  && $.browser.safari) ||
			   (browserString === 'mac'     && navigator.userAgent.indexOf('Mac') >= 0) ||
			   (browserString === 'ie6' && $.browser.msie && parseInt($.browser.version, 10) === 6) ||
			   (browserString === 'ie7' && $.browser.msie && parseInt($.browser.version, 10) === 7) ||
			   (browserString === 'pc_mozilla' && $.browser.mozilla && navigator.userAgent.indexOf('Windows') >= 0);
	},
	clientWidth : function (parentWindow) {

        var theWindow = parentWindow ? window.top.window : window,
            theDocument = parentWindow ? window.top.window.document : document;

        return this.f_filterResults(theWindow.innerWidth ? theWindow.innerWidth : 0,
			theDocument.documentElement ? theDocument.documentElement.clientWidth : 0,
			theDocument.body ? theDocument.body.clientWidth : 0);
	},
	clientHeight : function () {
	    return this.f_filterResults(window.innerHeight ? window.innerHeight : 0,
		    document.documentElement ? document.documentElement.clientHeight : 0,
		    document.body ? document.body.clientHeight : 0);
	},
	scrollLeft: function () {
	    return this.f_filterResults(window.pageXOffset ? window.pageXOffset : 0,
		    document.documentElement ? document.documentElement.scrollLeft : 0,
		    document.body ? document.body.scrollLeft : 0);
	},
	scrollTop : function (parentWindow) {

        var theWindow = parentWindow ? window.top.window : window,
            theDocument = parentWindow ? window.top.window.document : document;

        return this.f_filterResults(theWindow.pageYOffset ? theWindow.pageYOffset : 0,
			theDocument.documentElement ? theDocument.documentElement.scrollTop : 0,
			theDocument.body ? theDocument.body.scrollTop : 0);
	},
	f_filterResults : function (n_win, n_docel, n_body) {
		var n_result = n_win ? n_win : 0;
		if (n_docel && (!n_result || (n_result > n_docel))) {
			n_result = n_docel;
		}
		return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
	}
});

var EventCache = (function () {
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function (node, sEventName, fHandler) {
			listEvents.push(arguments);
		},
		flush : function () {
			var i, item;
			for (i = listEvents.length - 1; i >= 0; i = i - 1) {
				item = listEvents[i];

				if (item[0].removeEventListener) {
					item[0].removeEventListener(item[1], item[2], item[3]);
				}

				if (item[1].substring(0, 2) !== "on") {
					item[1] = "on" + item[1];
				}

				if (item[0].detachEvent) {
					item[0].detachEvent(item[1], item[2]);
				}

				item[0][item[1]] = null;
			}
		}
	};
}());


/* FUNCTIONS BOUND TO GLOBAL OBJECT - YUCK */


// old event code + some site specific stuff at the bottom
function addEvent(obj, type, fn) {
	if (obj.addEventListener) {
		obj.addEventListener(type, fn, false);
		EventCache.add(obj, type, fn);
	} else if (obj.attachEvent) {
		obj["e" + type + fn] = fn;
		obj[type + fn] = function () {
            obj["e" + type + fn](window.event);
        };
		obj.attachEvent("on" + type, obj[type + fn]);
		EventCache.add(obj, type, fn);
	} else {
		obj["on" + type] = obj["e" + type + fn];
	}
}

function goQuickLink(obj) {
    var url = obj.options[obj.selectedIndex].value;
    if (url) {
        window.location.href = url;
    } else {
        //alert("Please make a selection.");
    }
    return false;
}

function expandCol(theTR, img) {
	var dataTR = document.getElementById(theTR);
	if (dataTR.style.display === 'block' || dataTR.style.display === '') {
		dataTR.style.display = "none";
		img.src = '/images/butFullRev.gif';
	} else {
		dataTR.style.display = "";
		img.src = '/images/butCloseRev.gif';
	}
}

function pop(url, width, height, popName, resize, left, top) {
	var date, args, winName = "mypop";
	if (popName) {
		winName = popName;
		if (popName == '1') {
			date = new Date();
			winName = date.getTime();
		}
	}
	if (!resize) {
        resize = 'yes';
    }
	args = "width=" + width + ",height=" + height + ", scrollbars=yes, left=" + left + ", top=" + top;
	window.open(url, winName, "resizable=" + resize + ",toolbar=no," + args);
}

function nopop(url, winName, args) {
    window.location.href = url;
}

function imgSwap(objImg, imgName) {
	objImg.src = "/images/tabs/" + imgName;
}

function HeaderImgSwap(objImg, imgName) {
    objImg.src = imgName;
}


var submitClicked = false, activeForm = null;

function submitIt() {
	activeForm.submit();
	return false;
}

function simpleDisableButton(f) {
	if (!submitClicked) {
		activeForm = f;
		submitClicked = true;
		window.setTimeout(submitIt, 250);
	} else {
		return false;
	}
}

function disableButton(b, f, bt) {
	if (!submitClicked) {
		if (bt) {
			bt.value = "1";
		} else {
			var submitMessage = "  Please Wait...  ";
			b.value = submitMessage;
		}
		activeForm = f;
		b.disabled = true;
		submitClicked = true;
		window.setTimeout(submitIt, 250);
	} else {
		return false;
	}
}

function checkandsubmit(submitForm) {
	if (!submitClicked) {
		submitClicked = true;
		submitForm.submit();
	}

    return false;
}

// called from some old flashes - SV 1/6/06
function stopPitch() {
	window.location.href = "/registration/1.html";
}

function doPopups() {
    var params = 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,';

    $('a.terms').click(function () {
        window.open(this.href, '', params + 'width=565,height=620');
        return false;
    });

    $('a.privacy').click(function () {
        window.open(this.href, '', params + 'width=765,height=500');
        return false;
    });

    $('a.dlmScreenshot').click(function () {
        window.open(this.href, '', params + 'width=320,height=310');
        return false;
    });

    $('a.showMe').click(function () {
        window.open(this.href, "", "top=40,left=40,width=630,height=350");
        return false;
    });
}

//add disable button function to upgrade buttons
function disableSub() {
	var thisForm, i, inputs = document.getElementsByTagName('input');
	for (i = 0; i < inputs.length; i = i + 1) {
		if (/disableButton2/.test(inputs[i].className)) {
			thisForm = inputs[i].parentNode;
			while (thisForm.nodeName.toLowerCase() !== "form") {
				thisForm = thisForm.parentNode;
			}

			inputs[i].onclick = function () {
				disableButton(this, thisForm, null);
				return false;
			};
		}
	}
}

function center() {
	if (document.getElementById("exitPop")) {
		var frameWidth, frameHeight;

        if (self.innerWidth) {
            frameWidth = self.innerWidth;
            frameHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientWidth) {
            frameWidth = document.documentElement.clientWidth;
            frameHeight = document.documentElement.clientHeight;
        } else if (document.body) {
            frameWidth = document.body.clientWidth;
            frameHeight = document.body.clientHeight;
        }
		self.moveTo((screen.width - frameWidth) / 2, (screen.height - frameHeight) / 2);
    }
}


/* GLOBAL DOCUMENT READY */


$(function () {
    addEvent(window, 'unload', EventCache.flush);    
    addEvent(window, 'load', center);
    addEvent(window, 'load', doPopups);
    addEvent(window, 'load', disableSub);
 	
    $('#dashboard li a').hover(
		function () {
			$(this).children('span.upgrade').show();
			$(this).css('cursor', 'pointer');
		},
		function () {
			$(this).children('span.upgrade').hide();
		}
    );
    if ($('.jsPageHref').length) {
        $('.jsPageHref').each(function () {
            var elem = $(this), link;
            link = elem.attr('href');

            if (link.indexOf('?js=false') > -1) {
                if (link.indexOf('?js=false&') > -1 || link.indexOf('?js=false#') > -1) {
                    elem.attr('href', link.replace('js=false', 'hasJs'));
                } else {
                    elem.attr('href', link.replace('?js=false', ''));
                }
            } else if (link.indexOf('&js=false') > -1) {
                elem.attr('href', link.replace('&js=false', ''));
            }
        });
    }

	$('.dartAd img').each(function () {
		var ad = $(this);

        if (ad.height() < 50) {
			ad.parents('.notice').find('span.adText').hide();
		}
	});

    if ($('#myselectbox').length && !$('#myselectbox').find('ul').length) {
        $('#myselectbox').selectbox({
            wrapper     : $('#search')
        });
    }    
});


