// ----------------------------------------------------------------------------
// AUTOSHRINE NETWORK
// (C) 2010 Skye Nott, F4 Systems <skye@F4.ca>

if (typeof console == "undefined") {
    window.console = {
        log: function () {}
    };
}

// ----------------------------------------------------------------------------
// A lot of our older users are double-clicking the submit button.
// Safari and IE7(!) seems to debounce Submit, but Firefox doesn't.
// NOTE: if the user hits the Back button, submit will still be disabled!

function asn_form_debounce(form)
{
	if (!form.submit.disabled) {
		form.submit.value = "Please Wait...";
		form.submit.disabled = true;
		form.submit();
		return true;
	} else {
		// Never actually reached since submit should be disabled...
		alert('Please only click the submit button once.');
		return false;	    
	}
}

// ----------------------------------------------------------------------------
/* Page Font Size Control (PFSC) Javascript */
/* Copyright (C) 2010 Skye Nott, F4 Systems */

/* This depends on site CSS specifying font-size using em ONLY, i
 * with a font-size in % in the body {}. Typically, one can use the
 * "body { font-size: 62.5%; }" pattern so that 1.0em = 10px
 */

var PFSC = function () {

/* Private configuration variables. */
var MIN_PCT 		= 50;
var MAX_PCT 		= 100;
var DEFAULT_PCT 	= 62.5;
var STEP_PCT 		= 0.07;
var DEBUG 		= false;
var COOKIE_NAME 	= "pfsc_pct";
var SAVE_ELEM_ID 	= "pfsc_save";
var SAVE_OK_FG 		= '#FFFFFF';
var SAVE_OK_BG 		= '#0C0000';
var SAVE_FAIL_FG 	= '#FFFFFF';
var SAVE_FAIL_BG 	= '#FF0000';


/* Private functions */

var getFontSize = function () {
	if (document.body.style.fontSize == "")
		return setFontSize(DEFAULT_PCT);
	return parseFloat(document.body.style.fontSize);
};

var setFontSize = function(sizepct) {
	document.body.style.fontSize = sizepct + "%";
	debugMessage("Set body size to " + sizepct + "%");
	return sizepct;
};

var loadCookie = function() {
	if (document.cookie.length < 1)
		return 0;
	c_start = document.cookie.indexOf(COOKIE_NAME + "=");
	if (c_start == -1)
		return 0;
	c_start = c_start + COOKIE_NAME.length + 1;
	c_end = document.cookie.indexOf(";", c_start);
	if (c_end==-1) c_end=document.cookie.length;
	value = unescape(document.cookie.substring(c_start,c_end));
	debugMessage("Get cookie " + COOKIE_NAME + " " + value + "%");
	return parseFloat(value);
};

var setCookie = function(value) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + 256); /* days */
	document.cookie = COOKIE_NAME + "=" + escape(value) + ";expires=" + exdate.toUTCString() + ";path=/";
	debugMessage("Set cookie " + COOKIE_NAME + " to " + value + "%");
	return true;
};

var addLoadEvent = function(func) {
	var oldonload = window.onload;
	if (typeof window.onload != "function")
		window.onload = func;
	else {
		window.onload = function() {
			func();
			oldonload();
		}
	}
};

var debugMessage = function(str) {
	if (DEBUG)
	    window.status = "PFSC: " + str;
};

var restoreAttributes = function(elem, fg, bg, value) {
	//alert("restoreAttributes fired!\nfg=" + fg + " bg=" + bg);
	if (!elem) return;
	elem.style.color = fg;
	elem.style.background = bg;
	elem.innerHTML = value;
};

/* http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/ */
var getStyle = function(oElm, strCssRule) {
	var strValue = "";
	if (document.defaultView && document.defaultView.getComputedStyle) {
		strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	} else if (oElm.currentStyle) {
		strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1) {
			return p1.toUpperCase();
		});
		strValue = oElm.currentStyle[strCssRule];
	}
	return strValue;
}

/* Construct public interface object */
return {
	init: function () {
		// No longer needed; page.php reads cookie and puts in HTML HEAD CSS.
		//addLoadEvent(this.loadFontSize);
	},
	
	increaseFontSize: function () {
		var newsize = getFontSize() * (1 + STEP_PCT);
		var rounded = Math.round(newsize * 100) / 100;
		setFontSize(Math.min(rounded, MAX_PCT));
		return this.saveFontSize();
	},
	
	decreaseFontSize: function() {
		var newsize = getFontSize() * (1 - STEP_PCT);
		var rounded = Math.round(newsize * 100) / 100;
		setFontSize(Math.max(rounded, MIN_PCT));
		return this.saveFontSize();
	},
	
	resetFontSize: function() {
		setFontSize(DEFAULT_PCT);
		return this.saveFontSize();
	},
	
	loadFontSize: function() {
		sizepct = loadCookie();
		if (sizepct) {
		    if (sizepct < MIN_PCT) { sizepct = MIN_PCT; }
		    if (sizepct > MAX_PCT) { sizepct = MAX_PCT; }
		    setFontSize(sizepct);
		} else {
		    sizepct = getFontSize();
		}
		debugMessage("Loaded " + sizepct + "%");
		return true;	
	},
	
	saveFontSize: function() {
		var sizepct = getFontSize();
		if (setCookie(sizepct)) {
			var elem = document.getElementById(SAVE_ELEM_ID);
			if (elem) {
				var oldfg = getStyle(elem, "color");
				var oldbg = getStyle(elem, "background");
				var oldvalue = elem.innerHTML;
				if (!oldfg) oldfg = 'inherit';
				if (!oldbg) oldbg = 'inherit';
				elem.innerHTML = 'Saved';
				elem.style.color = SAVE_OK_FG;
				elem.style.background = SAVE_OK_BG;
				window.setTimeout(function(){ restoreAttributes(elem, oldfg, oldbg, oldvalue) }, 400);
			}
		}
		debugMessage("Saved " + sizepct + "%");
		return true;	
	}
};

}();

// No longer needed; page.php reads cookie and puts in HTML HEAD CSS.
//PFSC.init();

// ----------------------------------------------------------------------------
// JQUERY

$(document).ready(function () {  
    var constants = {
        'ASN_ELEMID_NAV': '#asntoc'
    };

    // ASN Navigation
    // Based on http://jqueryfordesigners.com/fixed-floating-elements/
    
    //var navtop = $('#asntoc').offset().top - parseFloat($('#asntoc').css('marginTop').replace(/auto/, 0));
    var navtop = $('#floating-menu-bottom').offset().top;
    console.log("ASN Navigation navtop %d", navtop);
    $(window).bind('scroll', function onWindowScroll(event) {
        var nav = $('#asntoc');
        if (! nav) return;
        var x = $(this).scrollLeft();
        var y = $(this).scrollTop();
        //console.log("Scroll to y %d", y);
        
        // Move nav menu to fixed on long pages
        if (y >= navtop + 260) {
            // change position
            if (! nav.hasClass('fixed')) {
                if (jQuery.support.opacity) {
                    nav.hide()
                    nav.addClass('fixed');
                    nav.fadeIn(250);
                } else {
                    nav.addClass('fixed');
                }
            }
            // adjust for right scroll to prevent overlap
            //nav.css('margin-left', '-' + x + 'px');
            if (x == 0)
                nav.show();
            else
                nav.hide();
        } else {
            if (nav.hasClass('fixed')) {
                nav.removeClass('fixed');
            }
        }
        
        if ($('#asn-debug')) {
            var debugtop = $('#asn-debug').offset().top;
            if (y >= debugtop) {
                nav.hide();
            }
        }

        // Highlight nav menu as call-to-action if we hit the bottom
        if (0) {
        if (nav.hasClass('fixed') && x == 0 && $(window).scrollTop() == $(document).height() - $(window).height()) {
            nav.fadeOut(80);
            nav.fadeIn(80);
        }
        }
        
    });
    $(window).scroll();
});

// ----------------------------------------------------------------------------



