/*********************************************************************
	Ttow.js
	-------
	
	This is my toolkit...
	
	LM: 01-08-10
	@author Rafael G. http://elrafa.0fees.net
	@dependencies jQuery 1.3.2
	@version 2.0.2

**********************************************************************/
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]-->';		
		$head.prepend(iecc);		
	})();
	
	// Ttow jQuery extension //
	$.fn.Ttow = function () {
		var $jquery = this;			
		return  {
		
			chopWords : function (_noOfWords, _use3Dots) {
				var DEFAULT_NO_OF_WORDS_ALLOWED = 12,
					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 {
	
		Util : (function () {
			
			return {
			
				// * basename method
				basename : function (_filename) {						
					return (_filename) ? (function () {
						var p = _filename.split('/');
						return p[(p.length - 1)];
					})() : '';
				},
				
				// * getFileExtension method
				getFileExtension : function (_filename) {				
					var fname = this.basename(_filename),
						p = fname.split('.');						
					return $.trim(p[p.length - 1]);				
				},
			
				// * loadcss method
				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) {
					this.getFileExtension(_filename) === 'css' ? this.loadcss(_filename, _callback) : $.getScript(_filename, _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 />');
				}
				
			};
			
		})(),
		
		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');
				
				if (window.TtowBrowserIE6 !== undef) {
					chk.ie6 = true;
				}
				else if (window.TtowBrowserIE7 !== undef) {
					chk.ie7 = true;
				}
				// remove ie conditional script tags //
				if ($ie6ScriptTag.length > 0) { $ie6ScriptTag.remove(); }
				if ($ie7ScriptTag.length > 0) { $ie7ScriptTag.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),
				msie6 :   (UA.indexOf('msie 6') !== -1 || commentCheck4IE.ie6 !== false),
				msie7 :   (UA.indexOf('msie 7') !== -1 || commentCheck4IE.ie7 !== false),
				msie8 :   (UA.indexOf('msie 8') !== -1 && 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 = {}, qs1 = uri.split('?'), qs2,
				qs3, len=qs1.length, qs2len = 0,
				c, b;
			for (c=0;c<len;c++) {
				qs2 = qs1[c].split('&');
				qs2len = qs2.length;
				for (b=0;b<qs2len;b++) {
					if ('' !== $.trim(qs2[b])) {
						qs3 = qs2[b].split('=');
						QS[qs3[0]] = $.trim(qs3[1]);
					}
				}
			}
			
			// * makeQueryString method
			QS.makeQueryString = function (_o) {
				if (_o instanceof Object) {
					var qs = '?';
					for (var p in _o) {
						if (_o.hasOwnProperty(p) && !$.isFunction(_o[p])) {
							qs += p+'='+_o[p]+'&';
						}
					}
					return qs.replace(/&$/, '');
				}
			};
			
			return QS;			
		})(),

		hash : window.location.hash.replace(/^#/, '')

			
	
	};
		
})(window.jQuery);

 