/**
 * EFS.js
 * eFashionSolutions Meteor Library
 * 2008.05.12
 *
 * Description: Extends Prototype 1.6.0.2
 * @author TJ Eastmond <teastmond@efashionsolutions.com>
 */

var EFS = {
	version : '1.0.0',
	searchBoxReplace : '',
	requiredPrototypeVersion : '1.6',
	debug : false
};

/** Make sure we have the right version of Prototype loaded first.  Copied from Scriptaculos. */
if (typeof convertVersionString == 'undefined') {
	var convertVersionString = function(versionString) {
		var r = versionString.split('.');
		return parseInt(r[0]) * 100000 + parseInt(r[1]) * 1000 + parseInt(r[2]);
	}
}

if ((typeof Prototype == 'undefined') || (convertVersionString(Prototype.Version) < convertVersionString(EFS.requiredPrototypeVersion))) {
	throw("script.aculo.us requires the Prototype JavaScript framework >= " + Scriptaculous.REQUIRED_PROTOTYPE);
}

/**
 * EFS.onDomReady - attach JavaScript events to elements
 * before the page completely loads, but instead right
 * after the DOM is ready.
 * @author TJ Eastmond <teastmond@efashionsolutions.com>
 */
Object.extend(Event, {
	onReady : function(f) {
		if(document.body) f();
		else document.observe('dom:loaded', f);
	}
});

EFS.onDomReady = function(func) { Event.onReady(func); };

Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
Prototype.Browser.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7;
Prototype.Browser.IE8 = Prototype.Browser.IE && !Prototype.Browser.IE6 && !Prototype.Browser.IE7;

/**
 * More accurate a method to check for true mouse hover event
 * @author TJ Eastmond <teastmond@efashionsolutions.com>
 */
var mouseLeaveEnter = function(e, handler) {
	var t = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ? e.toElement : e.fromElement;
	while (t && t != handler) { t = t.parentNode; }
	return (t != handler);
};

/** EFS Shadowbox specific code
EFS.Shadowbox = function(options) {
	var opts = Object.extend({}, options || {});
	Shadowbox.init(opts);
};

EFS.CloseShadowbox = function() { Shadowbox.close(); }; */

EFS.closeTopBar = function() {
	var b = $('topAlertBar');
	if (b.visible()) {
		var method = arguments[0] || 'fade';
		if (method == 'fade') {
			b.fade({ duration : 0.3 });
		} else {
			b.hide();
		}
	}
};

EFS.onDomReady(function() {
	if ($('topAlertBar') && $('topAlertBar').visible()) {
		document.getElementsByClassName('statusclose')[0].onclick = function() { EFS.closeTopBar(1); };
		var timer = setTimeout(function() { EFS.closeTopBar(); clearTimeout(timer); }, 3000);
	}
});

/**
* Gets the elements from the query string as a hash
*
* You can use this to get the query string when the script is included:
* <script src="script.js?var1=foo&var2=bar"></script>
*
* @see scriptaculous.js
*
* @param  string src the name of your script
* @return Hash   the query
* @author Reha Sterbin <rsterbin@efashionsolutions.com>
*/
EFS.getQuery = function(src) {
	var regex = new RegExp(src + "(\\?.*)?$");
	var found = $A(document.getElementsByTagName("script")).findAll(function(s) {
		return (s.src && s.src.match(regex))
	});
	if (found.length > 0) {
		var query = found[0].src.replace(/.*\?/, '');
		return $H(query.toQueryParams());
	} else {
		return $H({});
	}
};

EFS.ajaxStatus = function(msg){
	if ($('topAlertBar')) { $('topAlertBar').remove(); }
	var div = new Element('div', {'id' : 'topAlertBar' , 'class' : 'statusbar'} );
	var statusMsg =  new Element('span', { 'class' : 'statusmsg' });
	statusMsg . innerHTML = msg;
	var close = new Element('span', { 'title' : 'Close This Message Bar', 'class' : 'statusclose' });
	close.innerHTML = 'close';

	div.insert({bottom : statusMsg});
	div.insert({bottom : close});
	$('toolsheader').insert({before : div});

	document.getElementsByClassName('statusclose')[0].onclick = function() { EFS.closeTopBar(1);};
	var timer = setTimeout(function() {
			EFS.closeTopBar();
			clearTimeout(timer);
			$('topAlertBar').remove()
	}, 3000 );
};

EFS.doAjax = function(target, params, callback, method){
	methodz = (method) ? method : 'post'
	myAjax = new Ajax.Request(
	target, {
		method: methodz,
		parameters: params,
		onComplete: function(transport){
			if (transport.responseText.indexOf('usernameLogin')> -1 ) {
				document.location = '/';
			} else if (transport.responseText.indexOf('Access Denied')> -1) {
				EFS.ajaxStatus('User Was Denied Access to Ajax functionality at ' + target);
			} else {
				if (EFS.debug == true) {
					alert('target = ' + target + "\n"
						+ 'params = ' + params + "\n"
						+ 'method = ' + methodz + "\n"
						+ 'result = ' + transport.responseText.stripTags()
					)
				}
				callback(transport)
			}
		}
	});
};

EFS.verifyNoXss= function(input) {
	if(input.value.match(/^[a-zA-Z0-9.-]+$/i)) {
		return true;
	} else {
		alert('You have entered an invalid value. Please try again.');
		input.value = '';
		return false;
	}
},

/**
 * Clear the search text on focus, and put it
 * back if the field is blank on blur
 * @author TJ Eastmond <teastmond@efashionsolutions.com>
 */
EFS.onDomReady(function() {
	$$('input#searchQuery').each(function(element) {
		Event.observe(element, 'focus', function() {
			EFS.searchBoxReplace = this.value;
			if (this.value == 'keyword search' || this.value == 'search') {
				this.value = '';
			}
		});
		Event.observe(element, 'blur', function() {
			if (this.value == '') {
				this.value = EFS.searchBoxReplace;
			}
		});
	});
});

/**
 * Shows an AJAX error and redirects, if required
 *
 * This method picks up AJAX errors reported by ajaxError() in controllers that
 * extend EFS_Controller_Tools_Base.  To use it, set this function as onFailure
 * on an ajax request:
 *
 * new Ajax.Request(url, {
 *     method: 'post',
 *     parameters: { var1: 'val1', var2: 'val2' },
 *     onSuccess: function (transport) {
 *         // do stuff...
 *     }
 *     onFailure: EFS.showAjaxError
 * });
 *
 * @param  Ajax.Response response the response
 * @author Reha Sterbin <rsterbin@efashionsolutions.com>
 */
EFS.showAjaxError = function(response) {
	var json = response.responseJSON;

	if (json.message) {
		var message = json.message;
	} else {
		var message = 'There has been an error.';
	}

	var errorMarkup = '<div style="width:100%; height:100%; background:#fff;">'
				 + '<div style="padding: 10px;">'
				 + '<h3>There has been an error</h3>'
				 + '<p>' + message + '</p>'
				 + '</div>'
				 + '<div style="text-align: center; font-size: 0.9em; margin-top: 30px;">'
				 + '<p>Please contact an administrator to report this error.<br />'
				 + 'When you close this message, you will be redirected.</p>'
				 + '</div>'
				 + '</div>';

	var lines = Math.round(message.length / 80);
	var height = 200 + ((lines - 1) * 30);
	Shadowbox.close();
	Shadowbox.open.bind(Shadowbox).delay(0.4, {
		content: errorMarkup,
		type:    'html',
		width:   300,
		height:  height,
		options: {
			modal: true,
			onClose: function () {
				if (json.redirect) {
					window.location = json.redirect;
				}
			}
		}
	});
};

/**
 * Sorts the elements in a select list
 *
 * @todo handle text sorts where more than one copy appears
 *
 * @param  Element el the select element
 * @author Reha Sterbin <rsterbin@efashionsolutions.com>
 */
EFS.sortSelectOptions = function(el, useThis) {
	if (el.nodeName != 'SELECT') {
		return;
	}
	var hashed = new Hash();
	var toSort = new Array();
	for (var i = 0; i < el.options.length; i++) {
		var opt = el.options[i];
		if (useThis == 'text') {
			hashed.set(opt.text, opt.value);
			toSort[toSort.length] = opt.text;
		} else {
			hashed.set(opt.value, opt.text);
			toSort[toSort.length] = opt.value;
		}
	}
	toSort.sort();
	toSort.each(function(key, index) {
		if (useThis == 'text') {
			el.options[index].text = key;
			el.options[index].value = hashed.get(key);
		} else {
			el.options[index].value = key;
			el.options[index].text = hashed.get(key);
		}
	});
}

EFS.initBgStretch = function() {
	var bgimg;
	var img_w;
	var img_h;
	var img_aspect;

	Event.observe(window, 'load', function() {
		bgimg = $('backgroundImg');
		InitBackgroundImage();
		Event.observe(window, 'resize', SetBackgroundImage);
	});

	var InitBackgroundImage = function() {
		img_w = bgimg.getWidth();
		img_h = bgimg.getHeight();
		img_aspect = img_w / img_h;
		SetBackgroundImage();
		bgimg.appear({ duration : .6 });
	};

	var SetBackgroundImage = function() {
		var window = document.viewport.getDimensions()
		var window_aspect = window.width / window.height;
		if (window_aspect > img_aspect) { // adjust the width
			bgimg.style.width = window.width + "px";
			bgimg.style.height = Math.round(window.width / img_aspect) + "px";
		} else { // adjust the height
			bgimg.style.width = Math.round(window.height * img_aspect) + "px";
			bgimg.style.height = window.height + "px";
		}
	};
};

EFS.onDomReady(function() {
	if (p = $('topnav_WhatsHot')) {
		p.parentNode.innerHTML += '<div style="margin-top:2px; width:115px; background:#C5AC2B; display:none;" id="asseenin_dd"><a style="background:#C5AC2B;" href="/catalog/0/all_asseenin">As Seen In</a></div>';
		Event.observe($('topnav_WhatsHot').parentNode, 'mouseover', function(e) {
			if (mouseLeaveEnter(e, this)) { $('asseenin_dd').style.display = 'block'; }
		});

		Event.observe($('topnav_WhatsHot').parentNode, 'mouseout', function(e) {
			if (mouseLeaveEnter(e, this)) { $('asseenin_dd').style.display = 'none'; }
		});
	}
});


/**
 * Home page JS
 */
var homepage = {};

(function() {

	homepage.init = function() {
		if ($('miniEmailInput')) {
			homepage.setDefault();
			Event.observe($('miniEmailInput'), 'click', homepage.clearEmail);
			Event.observe($('miniEmailInput'), 'blur', homepage.emailBlur);
		}
	};

	homepage.clearEmail = function() {
		if ( $('miniEmailInput').value == 'enter email address' ) {
			$('miniEmailInput').value = '';
		}
	};

	homepage.setDefault = function() {
		$('miniEmailInput').value = 'enter email address';
	};

	homepage.emailBlur = function() {
		if ($('miniEmailInput').value == '') {
			homepage.setDefault();
		}
	};

	EFS.onDomReady(function() {
		homepage.init();
	});

})();


