connectionSpeed = 0;

(function($){
	$.speechwriter = {
		version: '0.1',
		website: 'http://www.speech.com/',
		sections: { 
			'cms-index-index' : 'this.initHome()',
			'cms-page-view' : 'this.initCMS()',
			'catalog-category-view' : 'this.initCategory()',
			'catalog-product-view' : 'this.initProduct()',
			'checkout-cart-index' : 'this.initCart()',
			'onestepcheckout-index-index' : 'this.initCheckout()',
			'cms-sniffer' : 'this.initSniffer()'
		},
		init: function()
		{
			$('#nav li').first().addClass('first');
			$('#nav li').last().addClass('last');
			
			$('.quick-access #websiteSelect .i-change').bind('click', function(){
				$('.quick-access #websiteSelect .dropdown').toggle();	
			});
			
			$('.quick-access #currencySelect .i-change').bind('click', function(){
				$('.quick-access #currencySelect .dropdown').toggle();	
			});
			
			$('.link-remove').bind('click', function(){
				return confirm('Are you sure you would like to remove this item from the shopping cart?');
			});
			
			$.speechwriter.Utilities.external();
		},
		initSiteSection: function(section){
			var section = $('body').attr('class').split(' ')[1];
            if(section == 'cms-page-view'){
                var section = $('body').attr('class').split(' ')[2];
            }
			eval(this.sections[section]);
		},
		initHome: function(){
			$('.top-speeches').each(function(){
				$('li', this).first().addClass('first');
				$('li', this).last().addClass('last');
			});
		},
		initCMS: function(){},
		initCategory: function(){
			$('.samples-popup').colorbox({inline: true, href: '#samples-content', width: '640px', opacity: 0.7, top: '10px'});
		},
		initProduct: function(){
		},
		initCart: function(){
			//Redirect to No Cookies page
			Mage.Cookies.set('swCookieCheck', 'test');
			if (Mage.Cookies.get('swCookieCheck')) {
			    Mage.Cookies.clear('swCookieCheck');
			}
			else {
			    window.location = this.website + 'enable-cookies';
			}
			
			$(".apply-coupon").bind('click', function(event){
				event.preventDefault();
				discountForm.submit(false);	
			});
			
			$(".cancel-coupon").bind('click', function(event){
				event.preventDefault();
				discountForm.submit(true);	
			});
		},
		initCheckout: function(){
			$('.input-email input').change(function(){
				if(Validation.validate($(this)[0])){
					$.ajax({
						url : '/abandoned/index/saveCart/',
						data : { 
									email : $(this).val()
								},
						dataType : 'json',
						success : function(json){
							console.log(json.success);
						}
					});
				}
			});
		},
		initSniffer: function(){
			var ar_status = PluginDetect.isMinVersion('AdobeReader', '0', 'application/vnd.fdf');
            var AdobeReader = (ar_status >=0 ? true : false);
            var flash_version = PluginDetect.getVersion('Flash');
            var gotFlash =   (PluginDetect.isMinVersion('Flash', '0') >= 0 ? 'true' : 'false')
            var Java0Status = PluginDetect.isMinVersion('Java', '0', 'getJavaInfo.jar');
            var Java0Installed = Java0Status >=0 ? true : false;
            var JavaVersion = PluginDetect.getVersion('Java', 'getJavaInfo.jar');

            //Convert commas to dots
            $flash_version = flash_version.toString().replace(/\,/g, '.');
            $java_version = JavaVersion.toString().replace(/\,/g, '.');

            //Check if Flash is enbled and it's version 9 or above
            if(gotFlash == 'true')
            {
                //Check what flash version is installed
                $flash_array = $flash_version.split('.');
                $flash_number = $flash_array[0] + '.' + $flash_array[1];
                $flash_number =  parseFloat($flash_number);
                if($flash_number < 9) {
                    $flash_string = '<p class="warning">You need to update Flash to view some of our content. <br />Update your Flash Plugin for free: <a href="http://get.adobe.com/flashplayer/" target="_blank">Update Flash Plugin</a></p>';
                } else {
                    $flash_string = '<p class="correct">Flash is available. Your version is <strong>'+ $flash_version +'</strong></p>';
                }

            }
            else {
                $flash_string = '<p class="warning">You need to install Flash to view some of our content. <br />Install Flash for free: <a href="http://get.adobe.com/flashplayer/" target="_blank">Install Flash</a></p>';
            }

            //Check if Java is enbled and its 1.6 or above
            $java = Java0Installed.toString();
            if($java == 'true')
            {
                //Check what java version is installed
                //Split the values by the dot and join the first two values together
                $java_array = $java_version.split('.');
                $java_number = $java_array[0] + '.' + $java_array[1];
                $java_number =  parseFloat($java_number);
                if($java_number < 1.6) {
                    $java_string = '<p class="warning">You need to update Java to view some of our content. <br />Update your version of Java for free: <a href="http://www.java.com/en/download/index.jsp" target="_blank">Update Java</a></p>';
                } else {
                    $java_string = '<p class="correct">The Java plugin is available. Your version is <strong>'+ $java_version + '</strong></p>';
                }

            }
            else {
                $java_string = '<p class="warning">You need to install the Java plugin to view some of our content. <br />Install it for free: <a href="http://www.java.com/en/download/index.jsp" target="_blank">Install Java</a></p>';
            }

            //Output the Flash and Java Strings
            $('#ctl00_ContentPlaceHolder1_Panel_Intro').prepend('<h3 id="browser">Browser Information</h3><p class="correct">You\'re using ' + BrowserDetect.browser + ' ' + BrowserDetect.version + ' on ' + BrowserDetect.OS + '!</p><h3 id="flash">Flash Plugin Information</h3>'+ $flash_string +'<h3 id="java">Java Plugin Information</h3>'+$java_string);

			$(window).load(function(){
            if(connectionSpeed > 1){
                //Speed Test
                $('#ctl00_ContentPlaceHolder1_Panel_Intro').append('<h3 id="connection">Connection Speed Information</h3><p class="info">Your Connection Speed tested as: <strong>' + connectionSpeed + ' kbps.</strong><br /><br />Based upon this information your connection device is most likely a <strong>' + $.speechwriter.connectionType(connectionSpeed) + '</strong></p>');
                if(connectionSpeed < 57){
                    $('#ctl00_ContentPlaceHolder1_Panel_Intro').append('<p class="warning"><strong>Please note:</strong> Your connection speed is quite slow. You may not be able to use the site to its full potential.</p>');
                }
            }});

//            var fn = function() {
//                $get("ctl00_ScriptManager1_HiddenField").value = '';
//                Sys.Application.remove_init(fn);
//            };
//
//            Sys.Application.add_init(fn);
//            Sys.Application.initialize();
		},
		Utilities:
		{
			external: function() {
				$('A[rel*="external"]').click(function(e) {
					var url = $(this).attr('href');
					window.open(url);
					e.preventDefault();
				});
			}
		},
		Forms:
		{
			focus: function() {
				var prevLabel = '';
				$('.focus').focus(function() {
					if ( $.trim($(this).val()) == $(this).attr('title') ) {
						prevLabel = $(this).val();
						$(this).val('');
					}
				});
				$('.focus').blur(function() {
					if ( $(this).val() == '' ) {
						$(this).val(prevLabel);
					}
				});
			}
		},
		slider: function(options){
			var defaults = {
				selector:		'.slider',		
				prevId: 		'prevBtn',
				prevText: 		'Previous',
				nextId: 		'nextBtn',	
				nextText: 		'Next',
				controlsShow:	true,
				controlsBefore:	'',
				controlsAfter:	'',	
				controlsFade:	true,
				firstId: 		'firstBtn',
				firstText: 		'First',
				firstShow:		false,
				lastId: 		'lastBtn',	
				lastText: 		'Last',
				lastShow:		false,				
				vertical:		false,
				speed: 			1000,
				auto:			false,
				pause:			30000,
				continuous:		false, 
				numeric: 		false,
				numericId: 		'controls'
			}; 
			
			var options = $.extend(defaults, options);  
					
			$(options.selector).each(function() {  
				var obj = $(this); 				
				var s = $("ul li", obj).length;
				var w = $("ul li", obj).width(); 
				var h = $("ul li", obj).height(); 
				var clickable = true;
				obj.width(w); 
				obj.height(h); 
				obj.css("overflow","hidden");
				var ts = s-1;
				var t = 0;
				$("ul", obj).css('width',s*w);			
				
				if(options.continuous){
					$("ul", obj).prepend($("ul li:last-child", obj).clone().css("margin-left","-"+ w +"px"));
					$("ul", obj).append($("ul li:nth-child(2)", obj).clone());
					$("ul", obj).css('width',(s+1)*w);
				};				
				
				if(!options.vertical) $("li", obj).css('float','left');
									
				if(options.controlsShow){
					var html = options.controlsBefore;				
					if(options.numeric){
						html += '<ol class="'+ options.numericId +'"></ol>';
					} else {
						if(options.firstShow) html += '<span class="'+ options.firstId +'"><a href=\"javascript:void(0);\">'+ options.firstText +'</a></span>';
						html += ' <span class="'+ options.prevId +'"><a href=\"javascript:void(0);\">'+ options.prevText +'</a></span>';
						html += ' <span class="'+ options.nextId +'"><a href=\"javascript:void(0);\">'+ options.nextText +'</a></span>';
						if(options.lastShow) html += ' <span id="'+ options.lastId +'"><a href=\"javascript:void(0);\">'+ options.lastText +'</a></span>';				
					};
					
					html += options.controlsAfter;						
					$(obj).after(html);										
				};
				
				if(options.numeric){									
					for(var i=0;i<s;i++){						
						$(document.createElement("li"))
							.attr('class', options.numericId + (i+1))
							.html('<a rel='+ i +' href=\"javascript:void(0);\">'+ (i+1) +'</a>')
							.appendTo($("."+ options.numericId))
							.click(function(){							
								animate($("a",$(this)).attr('rel'),true);
							}); 												
					};							
				} else {
					$("a","."+options.nextId).click(function(){		
						animate("next",true);
					});
					$("a","."+options.prevId).click(function(){		
						animate("prev",true);				
					});	
					$("a","."+options.firstId).click(function(){		
						animate("first",true);
					});				
					$("a","."+options.lastId).click(function(){		
						animate("last",true);				
					});				
				};
				
				function setCurrent(i){
					i = parseInt(i)+1;
					$("li", "." + options.numericId).removeClass("current");
					$("li." + options.numericId + i).addClass("current");
				};
				
				function adjust(){
					if(t>ts) t=0;		
					if(t<0) t=ts;	
					if(!options.vertical) {
						$("ul",obj).css("margin-left",(t*w*-1));
					} else {
						$("ul",obj).css("margin-left",(t*h*-1));
					}
					clickable = true;
					if(options.numeric) setCurrent(t);
				};
				
				function animate(dir,clicked){
					if (clickable){
						clickable = false;
						var ot = t;				
						switch(dir){
							case "next":
								t = (ot>=ts) ? (options.continuous ? t+1 : ts) : t+1;						
								break; 
							case "prev":
								t = (t<=0) ? (options.continuous ? t-1 : 0) : t-1;
								break; 
							case "first":
								t = 0;
								break; 
							case "last":
								t = ts;
								break; 
							default:
								t = dir;
								break; 
						};	
						var diff = Math.abs(ot-t);
						var speed = diff*options.speed;						
						if(!options.vertical) {
							p = (t*w*-1);
							$("ul",obj).animate(
								{ marginLeft: p }, 
								{ queue:false, duration:speed, complete:adjust }
							);				
						} else {
							p = (t*h*-1);
							$("ul",obj).animate(
								{ marginTop: p }, 
								{ queue:false, duration:speed, complete:adjust }
							);					
						};
						
						if(!options.continuous && options.controlsFade){					
							if(t==ts){
								$("a","."+options.nextId).addClass('inactive');
								$("a","."+options.lastId).addClass('inactive');
							} else {
								$("a","."+options.nextId).removeClass('inactive');
								$("a","."+options.lastId).removeClass('inactive');					
							};
							if(t==0){
								$("a","."+options.prevId).addClass('inactive');
								$("a","."+options.firstId).addClass('inactive');
							} else {
								$("a","."+options.prevId).removeClass('inactive');
								$("a","."+options.firstId).removeClass('inactive');
							};					
						};				
						
						if(clicked) clearTimeout(timeout);
						if(options.auto && dir=="next" && !clicked){;
							timeout = setTimeout(function(){
								animate("next",false);
							},diff*options.speed+options.pause);
						};
				
					};
					
				};
				// init
				var timeout;
				if(options.auto){;
					timeout = setTimeout(function(){
						animate("next",false);
					},options.pause);
				};		
				
				if(options.numeric) setCurrent(0);
			
				if(!options.continuous && options.controlsFade){					
					$("a","."+options.prevId).addClass('inactive');
					$("a","."+options.firstId).addClass('inactive');				
				};				
				
			});
		  
		},
        drawCSImageTag: function( fileLocation, fileSize, imgTagProperties ) {
            start = (new Date()).getTime();
            loc = fileLocation + '?t=' + escape(start);
            document.write('<img src="' + loc + '" ' + imgTagProperties + ' onload="connectionSpeed=jQuery.speechwriter.computeConnectionSpeed(' + start + ',' + fileSize + ');">');
            return;
        },
        connectionType: function(speed) {
            // This function returns a string describing the connection type
            // being used by the user-agent hitting the page.
            SLOW_MODEM = 15;
            FAST_MODEM = 57;
            ISDN_MODEM = 120;
            if (speed) {
                if (speed < SLOW_MODEM) {
                    return "Slow Modem";
                } else if (speed < FAST_MODEM) {
                    return "Fast Modem";
                } else if (speed < ISDN_MODEM) {
                    return "ISDN Modem";
                } else {
                    return "partial T1 or greater connection";
                }
            }
            else {
                return "Undetermined Connection";
            }
        },
        computeConnectionSpeed: function( start, fileSize ) {
            end = (new Date()).getTime();
            connectSpeed = (Math.floor((((fileSize * 8) / ((end - start) / 1000)) / 1024) * 10) / 10);
            return connectSpeed;
        }
	}

	$(function() {
		$.speechwriter.init();
		$.speechwriter.initSiteSection();
	});

})(jQuery.noConflict());
