/**
 * Javascript - jQuery enabled
 * 
 * @package BMC
 * @subpackage Media
 */

jQuery(document).ready(function($) {

	/* BMC Browser Detection */
	
	//A. Target Safari
	if( $.browser.safari ) {}
	
	//B. Target anything above IE6
	if ($.browser.msie && $.browser.version > 6 ) {
		
		
	}
	
	//C. Target IE6 and below
	if ($.browser.msie && $.browser.version <= 6 ) {alert('You are using an older version of Internet Explorer than this site supports.  Please download a newer version of IE, Firefox, Safari or Chrome to view this site correctly.') }
	
	//D. Target Firefox 2 and above
	if ($.browser.mozilla && $.browser.version >= "1.8" ) {}
	
	/* BMC Twitter Widget */
		
	$("<div id='tweet'></div>").hide().appendTo("#widgetTweets").lastTwitterMessage('bethbutler');
	
		
	/* BMC Sidebar Toggling */
	
	var widgetStates = [];
	
	initWidgetToggle();
	
	function initWidgetToggle() {
		$sidebarWidgets = $('.sidebarWidget');
		var numWidgets = $sidebarWidgets.length;
		
		var cookieReturn = getCookie();
		if (cookieReturn) {
			cookieReturnArray = cookieReturn.split(',');
			widgetStates=cookieReturnArray;
		} else {
			widgetStates = [];
			for (var i = 0; i < numWidgets; i++) {
				widgetStates.push("open");
			}
		}

		$sidebarWidgets.each( function(i) {
			if ($(this).hasClass("commentBubble")) { return;}
			
			$(this).find('.sidebarWidgetTop').bind('click', toggleWidget).css({'cursor' : 'pointer'});
			$(this).find('.sidebarWidgetTop').prepend('<div class="sidebarToggle"></div>');
			$(this).find('.sidebarWidgetTop').bind('mouseover', function() {
				$(this).find('.sidebarToggle').css({'background-position' : 'bottom right'});
			});
			$(this).find('.sidebarWidgetTop').bind('mouseout', function() {
				$(this).find('.sidebarToggle').css({'background-position' : 'top right'});
			});
			
			$(this).attr("i", i);
			
			// Check cookie for closed widgets
			if (widgetStates[i] == "closed") {
				closeWidget($(this), 0);
				$(this).find('.sidebarToggle').css({'background-position' : 'top left'});
			}
			
		});
		
		
	}
	
	
	
	
	function toggleWidget() {
		if (!$(this).parent().hasClass("closedWidget")) {
			closeWidget($(this).parent(), 300);
		} else {
			openWidget($(this).parent(), 300);
		}
	}
	
	function closeWidget($widget, speed) {
		
		if (!$widget.attr("origHeight")) $widget.attr("origHeight", $widget.find('.sidebarWidgetBody').height()); // Prevents errors on multiple clicking
		
		$widget.find('.sidebarWidgetBody').children().children().animate({'opacity' : 0}, speed, "swing", function() {
				$(this).css({'visibility': 'hidden'});
			});
		$widget.find('.sidebarWidgetBody').animate({'height' : 0}, speed);
		$widget.addClass("closedWidget");
		
		// change toggle image
		$widget.find('.sidebarWidgetTop').find('.sidebarToggle').css({'background-position' : 'bottom left'});
		$widget.find('.sidebarWidgetTop').bind('mouseover', function() {
			$(this).find('.sidebarToggle').css({'background-position' : 'bottom left'});
		});
		$widget.find('.sidebarWidgetTop').bind('mouseout', function() {
			$(this).find('.sidebarToggle').css({'background-position' : 'top left'});
		});
		
		// TODO make dependent on cookie
		widgetStates[$widget.attr("i")] = "closed";		
		updateCookie();
		
	}
	
	function openWidget($widget, speed) {
		$widget.find('.sidebarWidgetBody').animate({'height' : $widget.attr("origHeight")}, speed);
		$widget.find('.sidebarWidgetBody').children().children().css({'visibility' : 'visible'}).animate({'opacity' : 1}, speed);
		//$widget.find('.sidebarWidgetBottom').animate({'margin-top' : '-30px'}, speed);
		$widget.removeClass("closedWidget");
		
		// change toggle image
		$widget.find('.sidebarWidgetTop').find('.sidebarToggle').css({'background-position' : 'bottom right'});
		$widget.find('.sidebarWidgetTop').bind('mouseover', function() {
			$(this).find('.sidebarToggle').css({'background-position' : 'bottom right'});
		});
		$widget.find('.sidebarWidgetTop').bind('mouseout', function() {
			$(this).find('.sidebarToggle').css({'background-position' : 'top right'});
		});
		
		widgetStates[$widget.attr("i")] = "open";
		updateCookie();
	}
	
	/* Cookie Stuff*/
	
	function getCookie() {
		if (document.cookie.length > 0){
			startString = "widgetStates=";
			c_start = document.cookie.indexOf(startString);
			
			if (c_start != -1) {
				c_start = c_start + startString.length;
				c_end = document.cookie.indexOf(";", c_start);
				if (c_end == -1) c_end = document.cookie.length;
				return unescape(document.cookie.substring(c_start, c_end));
			}
		}
	}
	
	function updateCookie() {
		var exdate = new Date();
		exdate.setDate(exdate.getDate()+30);
		document.cookie="widgetStates=" + escape(widgetStates.toString()) + ";";
		//console.log(document.cookie);
	}
		
	/* Footer Expansion */
	/* var footerOpen = false;
	$('.footerContent #copyright a:first').bind('click', toggleFooter);
	
	function toggleFooter() {
		if (!footerOpen) {
			$('.footer').animate({'height' : '150px'}, 500);
			footerOpen = true;
		} else  {
			$('.footer').animate({'height' : '42px'}, 500);
			footerOpen = false;
		}		
		return false;
	} */
	
	/* Google Voice */
	
	$('#widget-ask li#widgetAskVoicemail').click( function() {
		
		$(this).slideUp("normal").hide().after('<div id="googleTalkWidget"><object type="application/x-shockwave-flash" data="https://clients4.google.com/voice/embed/webCallButton" width="230" height="85"><param name="movie" value="https://clients4.google.com/voice/embed/webCallButton" /><param name="wmode" value="transparent" /><param name="FlashVars" value="id=176d893b3692a9d016a59b68b5193598a7fd8041&style=0" /></object></div>').focus();
		
		return false;
		
	});
	
	
	/* Syndication Form Validation */
	$('#widget-syndication-content input#email').focus(clearText);
	/*
	$('#widget-syndication-content li#form').animate({'height' : '0', 'opacity' : '0'}, 300).hide();
	$('#widget-syndication-content .feedList li#email a').click(function() { 
		$('#widget-syndication-content li#form').animate({'height' : '50', 'opacity' : '1'}, 300);
			$('#widget-syndication-content input#email').focus();
		return false;
	});
	*/
	$('#widget-syndication-content #submit').click(function() {
		$('#widget-syndication-content .error').hide();	
		var hasError = false;
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		
		var emailFromVal = $('#widget-syndication-content input#email').val();
		if (emailFromVal == '' || emailFromVal == 'your email here') {
			$('#widget-syndication-content input#email').after('<span class="error">You forgot to enter your email address.</span>').focus();
			hasError = true;
		} else if (!emailReg.test(emailFromVal)) {
			$('#widget-syndication-content input#email').after('<span class="error">Please enter a valid email address.</span>').focus();
			hasError = true;
		}
				
		if(hasError == false) {
			$(this).fadeOut("normal").hide();
			$('#widget-syndication-content input#email').slideUp();
			regURL = 'http://feedburner.google.com/fb/a/mailverify?uri=BigMouthConsulting&email=' + emailFromVal;
			$('#widget-syndication-content input#email').after('<h2>Thank You!</h2>').focus();
			window.open(regURL, 'popupwindow', 'scrollbars=yes,width=550,height=520');
			//return true;
			
			
		}
						
		return false;
		
	});
	
	
	/* Question Submit Form Validation */
	$('#widget-ask-content textarea#question').focus(function() {
		if ($(this).text() == "enter a question here" ) {
			$(this).css({'text-align' : 'left'});
			$(this).text('');
		}
	});
	$('#widget-ask-content input#email').focus(clearText);
	
	
	function clearText() {
		$(this).attr('value', '');
	}
	
	function validateForm() {
		return false;
	}
	
	$('#widget-ask-content #submit').click(function() {
		$('#widget-ask-content .error').hide();	
		var hasError = false;
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		
		
		
		var emailFromVal = $('#widget-ask-content input#email').val();
		if (emailFromVal == '' || emailFromVal == 'your email here') {
			$('#widget-ask-content input#email').after('<span class="error">You forgot to enter your email address.</span>').fadeIn("normal").focus();
			hasError = true;
		} else if (!emailReg.test(emailFromVal)) {
			$('#widget-ask-content input#email').after('<span class="error">Please enter a valid email address.</span>').fadeIn("normal").focus();;
			hasError = true;
		}
		
		var questionVal = $('#widget-ask-content textarea#question').val();
		if (questionVal == '' || questionVal == 'enter a question') {
			$('#widget-ask-content textarea#question').after('<span class="error">You forgot to ask a question!</span>').focus();;
			hasError = true;
		} 
		
		if(hasError == false) {
			$(this).hide();
			$('#widget-ask-content').append('<br/><img id="sendingEmail" src="http://blogplay.com/libs/thickbox/loadingAnimation.gif" alt="sending" style="margin:0px 0px 0px -5px"/>').fadeIn("normal");
			
			$.ajax({
				type:	"POST",
				url:	"/sophie/wp-content/themes/bigmouthconsulting/library/media/sendemail.php",
				data:	"emailTo=info@bigmouthconsulting.com&emailFrom=" + emailFromVal + "&subject=Inquiry on BigMouthConsulting.com&message=" + questionVal,
				error:	function(XMLHttpRequest, textStatus, errorThrown) {
					$('#widget-ask-content #sendingEmail').fadeOut("normal", function() {
						$('#widget-ask-content #question-form').slideUp("normal", function() {
							$('#widget-ask-content').append('<h2>Error...</h2><p>There was a problem submitting your inquiry.  Please use an alternate method of contacting us, above.</p>');
							});
						});
					},
				
				success:	function(msg) {
					$('#widget-ask-content #sendingEmail').fadeOut("normal", function() {
						$('#widget-ask-content #question-form').slideUp("normal", function() {
							$('#widget-ask-content').append('<h2>Thanks!</h2><p>Thank you for submitting your question! We will get back to you as soon as possible.</p>');
							});
						});
					}
			})
			
			/*
			$.post("wp-content/themes/bigmouthconsulting/library/media/sendemail.php",
				{ emailTo: "corey@coreybutler.net", emailFrom: emailFromVal, subject: "Inquiry - BigMouthConsulting.com", message: questionVal },
						function(data) {
							console.log("success");
							$('#widget-ask-content #sendingEmail').fadeOut("normal", function() {
								$('#widget-ask-content #question-form').slideUp("normal", function() {
									$('#widget-ask-content').append('<h2>Success</h2><p>Thanks for submitting your question! It was successful!</p>');
								});
							});
							
						}
			); */
		}
						
		return false;
		
	});
	
	/* Google Analytics */
	$('a').click(function () {
			var thisel = $(this);
			try
			{
				_gaq.push(['_trackEvent', thisel.parents().andSelf().filter('[id!=""]:first').get(0).id, 'clicked', (thisel.text() || thisel.children('img:first').attr('alt'))]);
			}
			catch (err) {}
		});
	
});