/*********************************************************************
	Ttow.js
	-------
	
	This is my toolkit...
	
	LM: 02-17-10
	@author Rafael G. http://elrafa.0fees.net
	@dependencies jQuery 1.3.2 <
	@version 2.1

**********************************************************************/
var Ttow = (function ($) {
	
	var undef,
		$head = $('head');
	
	var __error = function (_msg) {
		throw 'Ttow Error: [' + _msg + ']';
	};
	
	if ($ === undef) {
		__error('jQuery Library is not loaded!');
	}
	
	// inject ie browser detection comments for windows //
	// http://www.quirksmode.org/css/condcom.html
	(function () {		
		var iecc = '<!--[if IE 6]><script id="Ttow-Browser-ie6">var TtowBrowserIE6 = true;</script><![endif]-->' +
				   '<!--[if IE 7]><script id="Ttow-Browser-ie7">var TtowBrowserIE7 = true;</script><![endif]-->' +
			       '<!--[if IE 8]><script id="Ttow-Browser-ie7">var TtowBrowserIE8 = true;</script><![endif]-->';		
		$head.prepend(iecc);		
	})();
	
	// Ttow jQuery extension //
	$.fn.Ttow = function (_method, _parameters) {
		var $jquery = this,
		methods = {						
			chopWords : function (_parameter) {
				var DEFAULT_NO_OF_WORDS_ALLOWED = 12,
					_noOfWords = _parameter[0],
					_use3Dots = _parameter[1],
					noWrd = (_noOfWords !== undef) ? parseInt(_noOfWords, 10) : DEFAULT_NO_OF_WORDS_ALLOWED;	
									
				return  $jquery.each(function () {
					if ($.trim($(this).text()) !== '') {
						var $me = $(this),
							fromWordsArr = $me.text().split(' '),
							howManyWords = fromWordsArr.length,						
							trimmedWords = '';
						for (var i = 0; i < noWrd; i++) {
							if (typeof fromWordsArr[i] !== 'undefined') {
								trimmedWords += fromWordsArr[i] + ' ';
							}	
						}
						$me.text($.trim(trimmedWords) + ((_use3Dots && howManyWords > noWrd) ? '...' : ''));
					}
				});
			}						
		};
			
		return methods[_method](_parameters);	
		
	};
	
	return {
	
		Util : (function () {
			
			return {
				
				loadedScripts : [],
			
				// * basename method
				basename : function (_filename) {						
					return (_filename) ? (function () {
						var p = _filename.split('/');
						return p[(p.length - 1)].replace(/\?.{1,}$/, '');
					})() : '';
				},
				
				// * getFileExtension method
				getFileExtension : function (_filename) {				
					var fname = this.basename(_filename),
						p = fname.split('.');						
					return $.trim(p[p.length - 1]);				
				},
			
				// * loadcss method (barfs on expressions in IE)
				loadcss : function (_href, _callback) {
					/***
						The code in loadcss method is copied from xLazyLoader 1.3 - Plugin for jQuery
						Copyright (c) 2008 Oleg Slobodskoi (ajaxsoft.de)				
					*/
					_callback = _callback || function () {};					
					if ( $('link[href*="'+_href+'"]').length > 0) {
						_callback();
						return;
					}
					var link = $('<link rel="stylesheet" type="text/css" media="all" href="'+_href+'"></link>')[0];
					if ( Ttow.Browser.msie ) {
						link.onreadystatechange = function () {
							/loaded|complete/.test(link.readyState) && _callback();
						};
					} else if ( Ttow.Browser.opera ) {
						link.onload = _callback;
					} else {
						/** 
						 * Mozilla, Safari, Chrome 
						 * unfortunately it is impossible to check if the stylesheet is really loaded or it is "HTTP/1.0 400 Bad Request"
						 * the only way to do this is to check if some special properties  were set, so there is no error callback for stylesheets -
						 * it fires alway success
						 * 
						 * There is also no access to sheet properties by crossdomain stylesheets, 
						 * so we fire callback immediately
						 */
						
						var hostname = location.hostname.replace('www.',''),
							hrefHostname = /http:/.test(_href) ? /^(\w+:)?\/\/([^\/?#]+)/.exec( _href )[2] : hostname;
						hostname != hrefHostname && Ttow.Browser.mozilla ?  
							_callback()
							:  
							//stylesheet is from the same domain or it is not firefox
							(function(){
								try {
									link.sheet.cssRules;
								} catch (e) {
									cssTimeout = setTimeout(arguments.callee, 20);
									return;
								}
								_callback();
							})();
					}
										
					$head.get(0).appendChild(link);
				},
				
				// * require method
				require : function (_filename, _callback) {
					$(function () {
					_callback = _callback || function () {};	
					if ($.isArray(_filename)) {
						var i = 0,
							len = (_filename.length - 1),
							___handle = function () {
								if (i === len) { _callback(); }
								else { i++; ___r(); }
							},
							___r = function () {
								Ttow.Util.getFileExtension(_filename[i]) !== 'css' 
									? (function () {
										if ($.inArray(Ttow.Util.basename(_filename[i]), Ttow.Util.loadedScripts) < 0) {											
											 $.getScript(_filename[i], function () {
												___handle();
												Ttow.Util.loadedScripts.push(Ttow.Util.basename(_filename[i]));
											 });											 
										}
										else {
											___handle();
										}																			
									  })() 
									: Ttow.Util.loadcss(_filename[i], ___handle);
							};
						___r();
					}
					else {
						Ttow.Util.getFileExtension(_filename) === 'css' 
								? Ttow.Util.loadcss(_filename, _callback) 
								: (function () {
										if ($.inArray(Ttow.Util.basename(_filename), Ttow.Util.loadedScripts) < 0) {											
											 $.getScript(_filename, function () {
												_callback();
												Ttow.Util.loadedScripts.push(Ttow.Util.basename(_filename));
											 });											 
										}
										else {
											_callback();
										}																			
								  })();
					}
					});		
				},
				
				// * preload method
				preload : function (_imgs) {
					var o;
					_imgs = $.makeArray(_imgs);
					for (var i=0, len=_imgs.langth; i<len; i++) {
						o = new Image().src = _imgs[i];
					}
				},
				
				// * supplant method
				// http://javascript.crockford.com/remedial.html
				supplant : function (_pattern, _o) {
					// careful with the {your-text here} pattern
					return _pattern.replace(/{([^{}]*)}/g,
						function (a, b) {
							var r = _o[b];
							return typeof r === 'string' || typeof r === 'number' ? r : a;
						}
					);
				},
				
				// * entities method
				// http://javascript.crockford.com/remedial.html
				entities : function (_str) {
					return _str.replace(/&/g, "&amp;")
							   .replace(/</g,"&lt;")
							   .replace(/>/g, "&gt;")
							   .replace(/"/g, "&quot;")
							   .replace(/'/g, "&#039;");
				},
				// * deentities method
				deentities : function (_str) {
					return _str.replace(/&amp;/g, "&")
							   .replace(/&lt;/g,"<")
							   .replace(/&gt;/g, ">")
							   .replace(/&quot;/g, '"')
							   .replace(/&#039;/g, "'");
				},
				
				// * yield method
				yield : function (_callback) {
					window.setTimeout(_callback, 0);
				},
				
				// * randomize method
				randomize : function (_limit) {					
					parseInt(_limit, 10);
					_limit = (_limit+'' !== 'NaN') ? _limit : 10;
					return Math.floor(Math.random() * ((+_limit)+1));
				},
				
				// * empty method
				empty : function (_str) {
					return $.trim(_str) === '';
				},
				
				// * nl2br method
				nl2br : function (_str) {
					return (_str + '').replace(/\n/g, '<br />');
				}
				
			};
			
		})(),
		
		require : function (_filename, _callback) { // shortcut method, from Ttow.Util.require() to Ttow.require()  
			return this.Util.require(_filename, _callback);
		},
		
		BC : (function () {
		
		    // method used only on business catalyst sites //
			//(http://www.onlinebusinesswiki.com/index.php?title=Special_Instructions_Box#Advanced_-_Populating_the_textbox_using_JavaScript)
			return {				
				
				Product : {
					// * AddProductExtras method
					addProductExtras : function (_callback) {
						// http://businesscatalyst.com/ForumRetrieve.aspx?ForumID=52&TopicID=11584
						window.AddProductExtras = _callback;
					},
					
					// * parseProductTotal method: @return String
					parseProductTotal : function () {
						var $cartSummaryTable = $('table.cartSummaryTable'),
							total = '';
						if ($cartSummaryTable.length > 0) {
							total = $.trim($cartSummaryTable.find('.cartSummaryItem').text().replace(/\d{1,}\sitem\(s\),\sTotal:\s\$/, '').replace('View Cart', ''));
							return (/^[0-9.,]{1,}$/.test(total)) ? total : '0.00';						
						}
						else {
							return '0.00';
						}
					}
					
				},
				
				ShoppingCart : {
				    
					// * updateProductExtras method
					updateProductExtras : function (_hollaBack) {
						window.UpdateProductExtras = _hollaBack;
					},
					
					// * updateShipping method
					updateShipping : function (_hollaBack) {
						window.UpdateShipping = function (c,e,b) {
							// dirty code from BC
							//-------------------------------------------------------------------------------
							var d=document.getElementById("catCartDetails");
							if(d){var a=CMS.OrderRetrievev2.ServerSideUpdateShipping(e,c,b);
							if(a.value[0]){d.innerHTML=a.value[2]}if(a.value[1].length>0){alert(a.value[1])}}
							//-------------------------------------------------------------------------------
							
							// my code //
							_hollaBack();
						}
					}
				
				},
				
				// * alertOverride method
				alertOverride : function (_hollaBack) {
					var oldAlert = window.alert;
					window.alert = function (_msg, _useDefault) {
						if (_useDefault) {
							oldAlert(_msg);							
						}
						else {
							_hollaBack(_msg);
						}
					};
				}
				
			};
		
		})(),
		
		Browser : (function () {			
			var commentCheck4IE = (function () {
				var chk = {ie6 : false, ie7 : false},
					$ie6ScriptTag = $('#Ttow-Browser-ie6'),
					$ie7ScriptTag = $('#Ttow-Browser-ie7'),
					$ie8ScriptTag = $('#Ttow-Browser-ie8');
				
				if (window.TtowBrowserIE6 !== undef) {
					chk.ie6 = true;
				}
				else if (window.TtowBrowserIE7 !== undef) {
					chk.ie7 = true;
				}
				else if (window.TtowBrowserIE8 !== undef) {
					chk.ie8 = true;
				}
				// remove ie conditional script tags //
				if ($ie6ScriptTag.length > 0) { $ie6ScriptTag.remove(); }
				if ($ie7ScriptTag.length > 0) { $ie7ScriptTag.remove(); }
				if ($ie8ScriptTag.length > 0) { $ie8ScriptTag.remove(); }
				
				return chk;				
			})(),
			UA = navigator.userAgent.toLowerCase();
			
			// http://www.upsdell.com/BrowserNews/res_sniff.htm
			return {
				mozilla : (UA.indexOf('firefox') !== -1 || $.browser.mozilla),
				chrome :  (UA.indexOf('chrome/') !== -1),
				opera :   (UA.indexOf('opera') !== -1 && window.opera !== undef && window.opera instanceof Object || $.browser.opera),
				safari :  (UA.indexOf('safari') !== -1 && UA.indexOf('chrome/') === -1),
				msie :    (UA.indexOf('msie') !== -1 || $.browser.msie /*@cc_on || true@*/),
				msie6 :   (UA.indexOf('msie 6') !== -1 || commentCheck4IE.ie6 !== false),
				msie7 :   (UA.indexOf('msie 7') !== -1 || commentCheck4IE.ie7 !== false),
				msie8 :   (UA.indexOf('msie 8') !== -1 || commentCheck4IE.ie8 && document.documentMode === 8)
			};					
		})(),
		
		Qs : (function () {
			// output the query string from the uri as a property of the Ttow.Qs object
			var uri = self.location.href
				QS = {};			
			
			// * parse method
			QS.parse = function (qs) {
				/* 
					Code borrowed from:
					http://adamv.com/dev/javascript/querystring
					
					Client-side access to querystring name=value pairs
					Version 1.3
					28 May 2008					
					License (Simplified BSD):
					http://adamv.com/dev/javascript/qslicense.txt
				*/
				var params = {};
				if (qs == undefined) {
					qs = location.search.substring(1, location.search.length);
					// Turn <plus> back to <space>
					// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
						qs = qs.replace(/\+/g, ' ');			
				}
				if (qs.length == 0) return;
				// parse out name/value pairs separated via &
				var args = qs.split('&'),
					pair, name, value; 
				// split out each name=value pair
				for (var i = 0; i < args.length; i++) {
					 pair = args[i].split('=');
					 name = decodeURIComponent(pair[0]);
					
					 value = (pair.length==2)
						? decodeURIComponent(pair[1])
						: undefined;
					
					params[name] = value;
				}
				return params;
			};
			
			$.extend(QS, QS.parse()); // extend QS making the name/value pares a property of Ttow.Qs object
			
			// * makeQueryString method
			QS.makeQueryString = function (_o) {
				return '?' + $.param(_o);
			};
			
			return QS;			
		})(),

		hash : window.location.hash.replace(/^#/, ''),
		
		Store : (function () { // todo: not finished yet
			var storage = $.trim(top.name),
				data = '';
			if (storage !== '') {
				data = /Ttow\(.{1,}\)/.exec(storage);
				if (data) {
					data = data[0].replace(/^Ttow\(/, '')
								  .replace(/\)$/, '');
					data = Ttow.Qs.parse(data);
				}
			}
			
			return {
				init : function () {
				
				}
			};
			
		})()

			
	
	};
		
})(window.jQuery);

 
