// make it safe to use console.log always
(function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();)b[a]=b[a]||c})(window.console=window.console||{});

//var base = 'http://eaglestrategies.readysetrocket.com/';
window.mydebug = false;
var oldpathnames = new Array();
var videoPlaying = false;
var videoInProgress = true;

var is_firefox_below_4 = function() {
	if($.browser.mozilla) {
		return true;
	} else {
		return false;
	}
	return false;
}

var supports_bgcover = function(){
	if ($.browser.msie){
		return ( version_compare( $.browser.version, '9', '>=') )? true : false;
	}else if($.browser.webkit){
		return ( version_compare( $.browser.version, '533', '>=') )? true : false;
	}else if($.browser.mozilla){
		return ( version_compare( $.browser.version, '1.9.2', '>=') )? true : false;
	}
	return false;
}
jQuery(document).ready(function($){
	// Add browser body classes
	$.each( $.browser, function(i, val){ $('body').addClass( i + '-' + parseInt($.browser.version, 10) ); return false; } );

	$("#mobilesite").click(function(){
		document.cookie="mobile=true; path=/; domain=.eaglestrategies.readysetrocket.com;";
		window.location="/";
	});

	if( $.browser.msie ){
		document.body.scroll = "no";
	}
	$.address.init(function(event) {
		$.address.autoUpdate(true);
		//$.address.crawlable(true);
		$('a:not([href^=http])').not('[href^="mailto"]').address(function(){
			return $(this).attr('href').replace(/^#/, '');
		});
	}).change(function(event) {
		var pathnames = $.address.pathNames();
		if( pathnames[0] == undefined ){
			empty_page(); // collapse everything
		}else{
			if ( pathnames[0] != oldpathnames[0] ){ //we have page and aren't already on it
				load_page();
				oldpathnames[0] = pathnames[0];
				if (pathnames[1] != undefined){
					if ( pathnames[1] != oldpathnames[1] ){
						load_subpage();
						oldpathnames[1] = pathnames[1];
					}
				}else{
					empty_subpage(); //collapse subpage
				}
			}else{ // We are already on this page
				if ($.address.hash() != ''){
					page_scrollbar.scrollto('#page #'+$.address.hash());
					$('#navigation ul a.selected').removeClass('selected');
					$('#navigation ul a[href$="#'+$.address.hash()+'"]').addClass('selected');
				}
				if (pathnames[1] != undefined){ // if we have a subpage
					if ( pathnames[1] != oldpathnames[1] ){
						load_subpage();
						oldpathnames[1] = pathnames[1];
					}
				}else{ // we don't have a subpage
					empty_subpage(); //collapse subpage
				}
			}
		}
	});	
	
	
	$(".slideshow").simplestSlideShow({'timeOut': 10000, 'speed': 800});
	updateClock();
	var page_scrollbar = $('#page');
	page_scrollbar.tinyscrollbar();
	var subpage_scrollbar = $('#subpage');
	subpage_scrollbar.tinyscrollbar();
	
	var clock = setInterval('updateClock()', 20000 );
	
	// Try to initiate ShareThis
	try{
		stLight.options({ publisher:'e4b7d18e-feba-4c7b-9e74-aee147380d4c', offsetTop:'-50' });
	}catch(e){}

	$('#bg').removeAttr('alt');
	if(supports_bgcover()){
		$('#bg').remove();
	}
	$(window).resize(function() {
		page_scrollbar.update();
		subpage_scrollbar.update();
		if( !supports_bgcover() ){
			if($(window).width() > 2000 || $(window).height() > 1493){
				$('#bg').attr('src', 'images/bg-2600.jpg');
			}else if($(window).width() > 1440 || $(window).height() > 1095){
				$('#bg').attr('src', 'images/bg-2000.jpg');
			}else if($(window).width() > 1024 || $(window).height() > 729){
				$('#bg').attr('src', 'images/bg-1440.jpg');
			}else{
				$('#bg').attr('src', 'images/bg-1024.jpg');
			}
		}
	});
	
	/*
	$.stylesheetInit();
	*/
	$('.decrease-font').bind( 'click', function(e){
			//$.stylesheetSwitch('styles');
			$("body").removeClass("bigger");
			page_scrollbar.update();
			subpage_scrollbar.update();
			return false;
		}
	);
	$('.increase-font').bind( 'click', function(e){
			//$.stylesheetSwitch('bigger');
			$("body").addClass("bigger");
			page_scrollbar.update();
			subpage_scrollbar.update();
			return false;
		}
	);
	
	function empty_page(){
		$('#navigation .current-page').removeClass('current-page');
		$('#wrapper').animate({"right": "-852px"}, 440, function(){
			$('#search-state').selectBox('destroy');
			$('#subpage .content .overview').empty();
			$('#page .content .overview').empty();
			oldpathnames[0] = undefined;
			oldpathnames[1] = undefined;
		});
	}
	function empty_subpage(){
		$('#page .selected').removeClass('selected');
		$('#wrapper').animate({"right": "-301px"}, 440, function(){
			$('#subpage .content .overview').empty();
			oldpathnames[1] = undefined;
		});
	}
	function load_page(){
		$('#navigation .current-page').removeClass('current-page');
		var pathnames = $.address.pathNames();
		var value = '#/'+pathnames[0];
		//alert(value);
		$('#navigation a[href="'+value+'"]').parent().addClass('current-page');
		$('#wrapper').animate({"right": "-301px"}, 440);
		$('#page .scrollbar').fadeOut( 200 );

		var href = '/ajax.php?page='+pathnames[0]+'&referring_page='+oldpathnames[0];
		$('#page .content .overview').animate({opacity:0}, 200, function(){
			$('#page .spinner').fadeIn(200);
			$.get(href, function(response, status, xhr){
				$('#page .spinner').fadeOut(200);
				$('#page .content .overview').html(response);
				$('#page div.form input[type="checkbox"]').prettyCheckboxes();
				$('#page .content .overview').animate({opacity:1}, 200, function(){
					page_scrollbar.update();
					$('#page .scrollbar').fadeIn( 200 );
					init_forms('#page');
					//subpage_links();
					$('a:not([href^=http])').not('[href^="mailto"]').address(function(){
						return $(this).attr('href').replace(/^#/, '');
					});
					//accordians
					$('.accordian .heading').click(function(){
						if ($(this).next('.content').is(':hidden')){
							$(this).siblings('.content:visible').slideUp();
							$(this).next('.content').slideDown(400, function(){
								//page_scrollbar.update();
							});
						}else{
							$(this).next('.content').slideUp();
						}
					});
					// Scroll to anchor if needed
					if ($.address.hash() !== ''){
						page_scrollbar.scrollto('#page #'+$.address.hash());
						$('#navigation ul a.selected').removeClass('selected');
						$('#navigation ul a[href$="#'+$.address.hash()+'"]').addClass('selected');
					}else{
						$('#navigation ul a.selected').removeClass('selected');
						$('#navigation .current-page ul a:first').addClass('selected');
					}

					$('#search-state').selectBox();
					$('#search-state').selectBox('settings', { menuTransition: "fade", menuSpeed: "slow" });
					//$('#search-state').dropkick();

					if ( pathnames[0] == 'who-we-are' ) setup_who_we_are();
				});
			});
		});
	}
	function load_subpage(){
		$('#page .selected').removeClass('selected');
		var value = '#'+$.address.value();
		//alert(value);
		$('#page a[href="'+value+'"], #page a[href$="'+value+'"]').not('.no-selected').addClass('selected');
		$('#wrapper').animate({"right": "0"}, 290);
		$('#subpage .scrollbar').fadeOut( 200 );
		var pathnames = $.address.pathNames();
		var href = '/ajax.php?subpage='+pathnames[1]+'&parent='+pathnames[0];
		$('#subpage .content .overview').animate({opacity:0}, 200, function(){
			$('#subpage .spinner').fadeIn(200);
			$.get(href, function(response, status, xhr){
				$('#subpage .spinner').fadeOut(200);
				$('#subpage .content .overview').html(response);
				$('#subpage div.form input[type=checkbox]').prettyCheckboxes();
				$('#subpage .content .overview').animate({opacity:1}, 200, function(){
					subpage_scrollbar.update();
					$('#subpage .scrollbar').fadeIn( 200 );
					init_forms('#subpage');
					try{ 
						stButtons.locateElements();
					}catch(e){
					}
					//subpage_links();
					$('a:not([href^="http"])').not('[href^="mailto"]').address(function(){
						return $(this).attr('href').replace(/^#/, '');
					});
					//accordians
					$('#subpage .accordian .heading').click(function(){
						if ($(this).next('.content').is(':hidden')){
							$(this).siblings('.content:visible').slideUp();
							$(this).next('.content').slideDown(400, function(){
								//page_scrollbar.update();
							});
						}else{
							$(this).next('.content').slideUp();
						}
					});
				});
			});
		});
	}
	function setup_who_we_are(){
		// Advisor search
		getAdvisers('#adviser-featured-results', 'featured');
		getAdvisers('#adviser-profiles-results','profiles');
		$('#search-zip-code').focus(function(){
			$(this).select();
		});
		$('.adviser-search #search-zip-code').focus(function(){
			if ($(this).val() == 'Zipcode') $(this).val('');
		});
		$('.adviser-search #search-zip-code').blur(function(){
			if ($(this).val() === '') $(this).val('Zipcode');
		});
		$('#search-zip-code').keypress(function(e){
			if(e.which == 13){
				$('.adviser-featured').hide();
				$('#adviser-search-results').html('');
				getAdvisers('#adviser-search-results', 'zip', $(this).val());
			}
		});
		$('#search-go').click(function(){
			$('#adviser-search-results').html('');
			$('.adviser-featured').hide();
			getAdvisers('#adviser-search-results', 'zip', $('#search-zip-code').val());
		});
		$('#search-state').change(function(){
		    $('#adviser-search-results').html('');
			$('.adviser-featured').hide();
			getAdvisers('#adviser-search-results', 'state', $(this).val());
		});
		$('#btn-show-execs').click(function(e){
	        $('#executive-hidden').show();
			$('#btn-hide-execs').show();
			$(this).hide();
			var top = $('.content .overview').css('top');
			page_scrollbar.update();
			page_scrollbar.scrollToPos(top);
	    });
		$('#btn-hide-execs').click(function(){
			$('#executive-hidden').hide();
			$('#btn-show-execs').show();
			$(this).hide();
			var top = $('.content .overview').css('top');
			page_scrollbar.update();
			page_scrollbar.scrollToPos(top);
		});
		$('#btn-show-featured').click(function(e){
			$('#hidden-profiles').css('display','block');
	        $('#hidden-profiles').show();
	        $('#btn-hide-featured').show();
	        $(this).hide();
	        var top = $('.content .overview').css('top');
	        page_scrollbar.update();
	        page_scrollbar.scrollToPos(top);
	    });
		$('#btn-hide-featured').hide();
	    $('#btn-hide-featured').click(function(){
	        $('#hidden-profiles').hide();
	        $('#btn-show-featured').show();
	        $(this).hide();
	        var top = $('.content .overview').css('top');
	        page_scrollbar.update();
	        page_scrollbar.scrollToPos(top);
	    });
	}
	$('#logo a').click(function(){
		empty_page();
		$.address.path('');
		return false;
	});
	$('.close').click(function(){
		$('#page .selected').removeClass('selected');
		empty_subpage();
		var pathnames = $.address.pathNames();
		$.address.path(pathnames[0]);
		return false;
	});
			
	$('#ticker .search .go').click(function(){
		if($('#ticker .search input').val().length > 1){
			$('#ticker .search img').fadeIn('slow');
			search_symbols($('#ticker .search input').val());
		}else{
			$('#ticker #results').animate({opacity: 'hide', bottom: 0}, 200);
		}
		return false;
	});
	
	$('#ticker .search form').submit(function(){
		return false;
	});
	$('#ticker .search label').click(function(){
		$(this).siblings('input').focus();
	});
	$('#ticker .search input').focus(function(){
		$(this).siblings('label:not(.checkbox)').fadeOut('fast');
	});
	$('#ticker .search input').blur(function(){
		if ($(this).val() === ''){
			$(this).siblings('label:not(.checkbox)').fadeIn('fast');
		}
	});
	$('#ticker .search input').empty();
	$('#ticker .search input').keyup(function(){
		if($(this).val().length > 1){
			$('#ticker .search img').fadeIn('slow');
			search_symbols($(this).val());
		}else{
			$('#ticker #results').animate({opacity: 'hide', bottom: 0}, 200);
		}
	});

	initListeners();

	if(is_firefox_below_4()){
		$('#video_player').html($('#player'));
		$('#video_player').css('display','none');
	}
	

	function getAdvisers(dest,action,param){
		var data = 'action=' + action;
		if(action == 'zip'){
			data += '&zip=' + param;
		}
		else if(action == 'state'){
			data += '&state=' + param;
		}
		var parameters = 
		$.getJSON('/admin-tool/findAgents.php?' + data, function(results){
			if(results.response === true){
				if(action == 'featured'){
					$(dest).html('<h1>Advisers Near ' + results.city + '</h1>');
					displayAdvisers(dest, results.result_set, action);
				}
				else if(action == 'profiles') {
					displayProfiles(dest, results.result_set, action);
				}
				else{
					$(dest).html('<p>Results for ' + param + '</p>');
					displayAdvisers(dest, results.result_set, action);
				}
				
				//console.log(results.result_set);
			}
			else {
				$(dest).html('<p>No Results</p>');
			}
		});
	}
	function displayAdvisers(dest, data, action){
		var resultBlock = $(dest);
		var i = 0;
		var page = 1;
		var resultHtml = '<div class="page page1"><ol>';
		$.each(data, function(idx, office){
			if (typeof office.distance != "undefined"){
				var distance = Math.round(office.distance);
				if(distance === 0){
					distance = "< 1 mile";
				}
			}else{
				var distance = false;
			}
			if(typeof office.titles != 'undefined'){
				var titles = office.titles;
			}
			else {
				var titles = false;
			}
			if(typeof office.description != 'undefined'){
                var description = office.description;
            }
            else {
                var description = false;
            }
			//var website = (typeof office.website != "undefined" && office.website != null)? '<a href="'+office.website+'">View Website</a>' : '';
			var website = ( !empty(office.website) )? '<a href="'+office.website+'">View Website</a>' : '';
			var address = office.address1;
			if(office.address2 !== null && office.address2 !== ''){
				address += ', <br/> ' + office.address2;
			}
			var map_link = ' &emsp;<a class="show-map" href="">Map</a> ';
			// See http://code.google.com/apis/maps/documentation/staticmaps/ for details
			var map = '<img class="map" src="http://maps.google.com/maps/api/staticmap?&markers=color:green%7C'+office.latitude+','+office.longitude+'&zoom=14&size=390x286&sensor=false" width="390" height="286" />';
			if(typeof office.email != "undefined" && office.email !== null){
				resultHtml += '<li class="adviser-result">' +
				'<h3 class="name"><a href="mailto:'+office.email+'">' + office.first_name + ' ' + office.middle_name + ' ' + office.last_name + '</a></h3>';
			}else{
				resultHtml += '<li class="adviser-result">' +
				'<h3 class="name">' + office.first_name + ' ' + office.middle_name + ' ' + office.last_name + '</h3>';
			}
			//console.log(typeof distance, distance);
			if(typeof office.bio != "undefined"){
				resultHtml += '<p>'+office.bio+'</p>';
			}
			
			resultHtml += '<p class="left">';
			if(distance != false) resultHtml += 'Distance: ' + distance + ' miles <br/>';
			if(website != '') resultHtml += website + '<br />';
			if(office.phone != '') resultHtml += office.phone + '<br />';
			resultHtml += "</p>";
			
			resultHtml += '<p class="right">' + address + '<br />' + office.city + ', ' + office.state + ' ' + office.zip + map_link + '</p>' + map;
			resultHtml += '</li>';
			i++;
			if(i == 5) {
				var start = i*page+1;
				page++;
				resultHtml += '</ol></div><div class="page page' + page + '"><ol start=' + start +'>';
				i=0;
			}
		});
		resultHtml += '</ol></div>';
		resultBlock.append(resultHtml);
		var pagerHtml;
		if(page > 1){
			pagerHtml = '<div class="pager"><ul><li>Page</li>';
			for(i=1;i<=page;i++){
				if ($('.page' + i).find('li').length) {
					var selected = '';
					if (i == 1) {
						selected = ' class="selected"';
					}
					pagerHtml += '<li' + selected + '><a href="javascript:void(0)" rel="' + i + '">' + i + '</a></li>';
				}
			}
			pagerHtml += '</ul></div>';
			resultBlock.append(pagerHtml);
			
			$('.pager a').click(function(){
				$('#adviser-search-results .page').hide();
				var pageNum = $(this).attr('rel');
				$('.pager li').removeClass('selected');
				$(this).parent().addClass('selected');
				$('#adviser-search-results .page'+pageNum).show();
				var top = $('.content .overview').css('top');
				page_scrollbar.update();
				page_scrollbar.scrollToPos(top);
			});
		}
		
		$('.show-map', resultBlock).click(function(){
			$(this).parent().siblings('.map').toggle();
			var top = $('.content .overview').css('top');
			page_scrollbar.update();
			page_scrollbar.scrollToPos(top);
			return false;
		});
		var top = $('.content .overview').css('top');
		page_scrollbar.update();
		page_scrollbar.scrollToPos(top);
	}
	
	function displayProfiles(dest, data, action){
		
		//console.log(data)
		$.each(data, function(idx, office){
			var html = '';
			html += '<a class="ctalarge';
			html += '" href="#/who-we-are/advisor-spotlight-' + office.id + '">';
			html += '<h2>' + office.first_name + ' ' + office.last_name + '<br><font size="-3">' + office.titles + '</font></h2>';
			//console.log(office);
			var description = ( office.short_description !== null )? office.short_description : office.description;
			description.replace( '<br/>', '[br/]' ).replace( '</p>', '[br/]' ).replace( /(<([^>]+)>)/ig, "" ).replace( '[br/]', '<br/>' );
			description = truncate( description, 24 );
			html += '<p rel="test">' + description.trim() + '</p></a>';
			//html += '<p rel="test">' + description.replace(/(([^\s]+\s+){14}).+/g, "$1...") + '.</p></a>';
			//html += '<p>' + office.description.replace(/(([^\s]+\s+){14}).+/, "$1...") + '.</p></a>';
			//html += '<p>' + office.description.split('.')[0] + '.</p></a>';
			if(idx > 2){
				$('#hidden-profiles').append(html);
			}
		    else{
			    $(dest).append(html);
			}
			
		});
		
		
		page_scrollbar.update();
        //page_scrollbar.scrollToPos(top);
		
	}

});

function scrollto(id){
	dest = $('#page #'+id).position();
	if (dest.top){
		maxtop = $('#page .overview').outerHeight() - $('#page .viewport').outerHeight();
		//alert(dest.top);
		if (dest.top < maxtop){
			$('#page .overview').css('top', dest.top * -1);
		}else{
			$('#page .overview').css('top', maxtop * -1);
		}
		$('#page #'+id).focus();
	}
}

function init_forms(area){
	// forms
	var emailRegex = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])",'');
	$('div.form label').click(function(){
		$(this).siblings('input').focus();
	});
	$('div.form input').focus(function(){
		$(this).siblings('label:not(.checkbox)').fadeOut('fast');
	});
	$('div.form input:not(.required, .email)').blur(function(){
		if ($(this).val() === ''){
			$(this).siblings('label:not(.checkbox)').fadeIn('fast');
		}else{
			$(this).not('.checkbox, .submit').siblings('span.valid').remove();
			$(this).not('.checkbox, .submit').after('<span class="valid">Valid</span>');
		}
	});
	
	$('div.form input.required' ).blur(function(){
		if ($(this).val() !== '' ){
			$(this).not('.checkbox, .submit').siblings('span').addClass('valid').removeClass('invalid');
			$(this).addClass('valid').removeClass('invalid');
		}else{
			$(this).siblings('label:not(.checkbox)').fadeIn('fast');
			$(this).not('.checkbox, .submit').siblings('span').addClass('invalid').removeClass('valid');
			$(this).addClass('invalid').removeClass('valid');
		}
	});
	$('div.form input.email' ).blur(function(){
		if ($(this).val() !== '' ){
			if ( emailRegex.test( $(this).val() ) ){
				$(this).not('.checkbox, .submit').siblings('span').addClass('valid').removeClass('invalid');
				$(this).addClass('valid').removeClass('invalid');
			}else{
				$(this).not('.checkbox, .submit').siblings('span').addClass('invalid').removeClass('valid');
				$(this).addClass('invalid').removeClass('valid');
			}
		}else{
			$(this).siblings('label:not(.checkbox)').fadeIn('fast');
			$(this).not('.checkbox, .submit').siblings('span').addClass('invalid').removeClass('valid');
			$(this).addClass('invalid').removeClass('valid');
		}
	});
	
	$("form.cmajax button:submit").click(function() {
		//alert("test");
		$('form.cmajax').submit(function() { return false; });

		var formAction = $("form.cmajax").attr("action");
		var id = "pddktu";
		var emailId = id + "-" + id;
		
		if (!checkEmail(emailId)) {
			//alert("Please enter a valid email address");
			return;
		}
		
		var str = $("form.cmajax").serialize();
		var serialized = str + "&action=" + formAction;
		
		// Submit the form via ajax
		$.ajax({
		url: "proxy.php",
		type: "POST",
		dataType: "text",
		async: false,
		data: serialized,
		/*
		error: function(jqXHR, textStatus, errorThrown) {
	      console.log('AJAX call failed: '+textStatus+' '+errorThrown); //  or you can do: alert('AJAX call failed: '+textStatus+' '+errorThrown');
	    },
	    */
		success: function(data){
			// Server-side validation
			if (data.search(/invalid/i) != -1) {
				//alert( "fail" );
				$('form.cmajax').after('<p class="error">We ran into a problem with your form and were unable to submit it successfully.</p>');
			}else{
				//alert( "win" );
				$('form.cmajax').fadeOut(300, function(){
					$(area+' .error').remove();
					$(area+' .success').fadeIn();
				});
			}
		}
		});
    });
	
	$('form.ajax').ajaxForm({
		beforeSubmit: function(arr, $form, options) {
			// validate form
			var valid = true;
			$form.find('input.required:not(.checkbox, .submit)').each(function(){
				if(!$(this).hasClass('valid')){ 
					$(this).addClass('invalid').removeClass('valid').siblings('span').addClass('invalid').removeClass('valid');
					valid = false;
				}
			});
			if(valid){
				$form.find('.error').remove();
				return true;
			}else{
				return false;
			}
		},
		success: function(responseText, statusText, xhr, $form){
			if(responseText == 'success'){
				$form.fadeOut(300, function(){
					$(area+' .success').fadeIn();
				});
			}else{
				$form.after('<p class="error">We ran into a problem with your form and were unable to submit it successfully.</p>');
			}
		}
	});
}

function search_symbols(q){
	$.get('/ticker.php?action=search&q='+q, function(response, status, xhr){
		$('#ticker #results').html(response);
		$('#ticker .search img').fadeOut('slow');
		$('#ticker #results').animate({opacity: 'show', bottom: '80px'}, 300);
		$('#ticker #results tr').hover(
			function(){
				$(this).children('td').addClass('selected');
			}, function(){
				$(this).children('td').removeClass('selected');
			}
		);
		$('#ticker #results tr').click(function(){
			get_quote($(this).find('.symbol').text());
			$('#ticker .search input').val('').blur();
			$('#ticker #results').animate({opacity: 'hide', bottom: 0}, 200);
		});
	});
}

function get_quote(q){
	//alert(q);
	$('<li class="stock '+q+'"></li>').insertAfter('#ticker li.market_tracker');
	$.get('/ticker.php?action=quote&q='+q, function(response, status, xhr){
		$('#ticker .'+q).html(response).find('table').fadeIn('slow');
	});
}

function updateClock(){
	var currentTime = new Date();
	var currentHours = currentTime.getHours();
	var currentMinutes = currentTime.getMinutes();
	//var currentSeconds = currentTime.getSeconds();
	currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
	//currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;
	var timeOfDay = ( currentHours < 12 ) ? "am" : "pm";
	currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;
	currentHours = ( currentHours === 0 ) ? 12 : currentHours;
	var month_names = [];
		month_names[month_names.length] = "January";
		month_names[month_names.length] = "February";
		month_names[month_names.length] = "March";
		month_names[month_names.length] = "April";
		month_names[month_names.length] = "May";
		month_names[month_names.length] = "June";
		month_names[month_names.length] = "July";
		month_names[month_names.length] = "August";
		month_names[month_names.length] = "September";
		month_names[month_names.length] = "October";
		month_names[month_names.length] = "November";
		month_names[month_names.length] = "December";
	
	var currentTimeString = month_names[currentTime.getMonth()] + " " + currentTime.getDate() + " " + currentHours + ":" + currentMinutes + " " + timeOfDay;
	$('.market_tracker .date').html(currentTimeString);
}

jQuery.fn.fadeIn = function(speed, callback) { 
    return this.animate({opacity: 'show'}, speed, function() { 
        if (jQuery.browser.msie)  
            this.style.removeAttribute('filter');  
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
}; 

jQuery.fn.fadeOut = function(speed, callback) { 
    return this.animate({opacity: 'hide'}, speed, function() { 
        if (jQuery.browser.msie)  
            this.style.removeAttribute('filter');  
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
}; 

jQuery.fn.fadeTo = function(speed,to,callback) { 
    return this.animate({opacity: to}, speed, function() { 
        if (to == 1 && jQuery.browser.msie)  
            this.style.removeAttribute('filter');  
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
};

(function($){
  $.fn.simplestSlideShow = function(settings){
    var config = {
      'timeOut': 3000,
      'speed': 'normal'
    };
    if (settings) $.extend(config, settings);
    this.each(function(){
      var $elem = $(this);
      $elem.children(':gt(0)').hide();
      setInterval(function(){
        $elem.children().eq(0).fadeOut( config.speed )
        .next().fadeIn( config.speed )
        .end().appendTo($elem);
      }, config.timeOut );
    });
    return this;
  };
})(jQuery);

function checkEmail(email) { 
  var pattern = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  var emailVal = $("#" + email).val();
  return pattern.test(emailVal);
}

jQuery.fn.prettyCheckboxes = function(settings) {
	settings = jQuery.extend({
				checkboxWidth: 17,
				checkboxHeight: 17,
				className : 'prettyCheckbox',
				display: 'list'
			}, settings);

	$(this).each(function(){
		// Find the label
		$label = $('label[for="'+$(this).attr('name')+'"]');
		// Add the checkbox holder to the label
		$label.prepend("<span class='holderWrap'><span class='holder'></span></span>");
		// If the checkbox is checked, display it as checked
		if($(this).is(':checked')) { $label.addClass('checked'); }
		// Assign the class on the label
		$label.addClass(settings.className).addClass($(this).attr('type')).addClass(settings.display);
		// Assign the dimensions to the checkbox display
		$label.find('span.holderWrap').width(settings.checkboxWidth).height(settings.checkboxHeight);
		$label.find('span.holder').width(settings.checkboxWidth);
		// Hide the checkbox
		$(this).addClass('hiddenCheckbox');
		// Associate the click event
		$label.bind('click',function(){
			$('input[name="' + $(this).attr('for')+'"]').triggerHandler('click');
			if($('input[name="' + $(this).attr('for')+'"]').is(':checkbox')){
				$(this).toggleClass('checked');
				$('input[name="' + $(this).attr('for')+'"]').checked = true;
				$(this).find('span.holder').css('top',0);
			}else{
				$toCheck = $('input[name="' + $(this).attr('for')+'"]');
				// Uncheck all radio
				$('input[name="'+$toCheck.attr('name')+'"]').each(function(){
					$('label[for="' + $(this).attr('name')+'"]').removeClass('checked');	
				});
				$(this).addClass('checked');
				$toCheck.checked = true;
			}
		});
		$('input[name="' + $label.attr('for')+'"]').bind('keypress',function(e){
			if(e.keyCode == 32){
				if($.browser.msie){
					$('label[for="'+$(this).attr('name')+'"]').toggleClass("checked");
				}else{
					$(this).trigger('click');
				}
				return false;
			}
		});
	});
};

checkAllPrettyCheckboxes = function(caller, container){
	if($(caller).is(':checked')){
		// Find the label corresponding to each checkbox and click it
		$(container).find('input[type="checkbox"]:not(:checked)').each(function(){
			$('label[for="'+$(this).attr('name')+'"]').trigger('click');
			if($.browser.msie){
				$(this).attr('checked','checked');
			}else{
				$(this).trigger('click');
			}
		});
	}else{
		$(container).find('input[type="checkbox"]:checked').each(function(){
			$('label[for="'+$(this).attr('name')+'"]').trigger('click');
			if($.browser.msie){
				$(this).attr('checked','');
			}else{
				$(this).trigger('click');
			}
		});
	}
};
function version_compare (v1, v2, operator) {
    this.php_js = this.php_js || {};
    this.php_js.ENV = this.php_js.ENV || {};
    var i = 0,
        x = 0,
        compare = 0,
        vm = { 'dev': -6, 'alpha': -5, 'a': -5, 'beta': -4, 'b': -4, 'RC': -3, 'rc': -3, '#': -2, 'p': -1, 'pl': -1 },
        prepVersion = function (v) {
            v = ('' + v).replace(/[_\-+]/g, '.');
            v = v.replace(/([^.\d]+)/g, '.$1.').replace(/\.{2,}/g, '.');
            return (!v.length ? [-8] : v.split('.'));
        },
        numVersion = function (v) {
            return !v ? 0 : (isNaN(v) ? vm[v] || -7 : parseInt(v, 10));
        };
    v1 = prepVersion(v1);
    v2 = prepVersion(v2);
    x = Math.max(v1.length, v2.length);
    for (i = 0; i < x; i++) {
        if (v1[i] == v2[i]) {
            continue;
        }
        v1[i] = numVersion(v1[i]);
        v2[i] = numVersion(v2[i]);
        if (v1[i] < v2[i]) {
            compare = -1;
            break;
        } else if (v1[i] > v2[i]) {
            compare = 1;
            break;
        }
    }
    if (!operator) {
        return compare;
    }

    switch (operator) {
    case '>':
    case 'gt':
        return (compare > 0);
    case '>=':
    case 'ge':
        return (compare >= 0);
    case '<=':
    case 'le':
        return (compare <= 0);
    case '==':
    case '=':
    case 'eq':
        return (compare === 0);
    case '<>':
    case '!=':
    case 'ne':
        return (compare !== 0);
    case '':
    case '<':
    case 'lt':
        return (compare < 0);
    default:
        return null;
    }

   

}

// document.addEventListener("DOMContentLoaded", initListeners, false);

detectOrientation();
window.onorientationchange = detectOrientation;
function detectOrientation(){
	setThePlayerSize('#html5_video');		
}


function setThePlayerSize(id) {
	var player = $(id);
	var width = $(window).width();
	var height = $(window).height();
//	alert(height + window.innerHeight);
//	alert(width + window.innerWidth);
	var ratio = 814/578;

	if(height === 0) { height=window.innerHeight; }

	if(ratio > width/height) {
	  player.attr('height', height);
	  player.attr('width', height * ratio);
	} else {
	  player.attr('width', width);
	  player.attr('height', width/ratio);
	  $('#video_player').css('top', -(width/ratio - height)/2);
	}

	$('#progress, #play_button').css('top', height/2-30);
	$('#progress, #play_button').css('left', width/2-30);

	//$('#background').css('bottom','-1px');

//	alert(height+' '+width);

//	document.getElementById("view").setAttribute('content','user-scalable=yes, width=device-width, minimum-scale = 1, maximum-scale = 1');
//	$("#video_player").attr('width', width);
//	$("#video_player").attr('height', height);
//	alert(player.attr('height')+' '+player.attr('width') + ' ' + ratio + ' ' + width + ' ' + height);
	window.scrollTo(0, 1);
}

function initListeners() {
    var HTML5_video = document.getElementById('html5_video');
    try{
    HTML5_video.addEventListener('play', vimeo_on_play, false);
    HTML5_video.addEventListener('pause', vimeo_on_finish, false);
    HTML5_video.addEventListener('ended', vimeo_on_finish, false);
    HTML5_video.addEventListener('seeked', vimeo_on_play, false);
//    HTML5_video.addEventListener('timeupdate', video_playing, false);
//    HTML5_video.addEventListener('progress', video_in_progress, false);
    } catch(err) { var a; }
	setThePlayerSize('#html5_video');
	$(window).resize(function() {
		setThePlayerSize('#html5_video');
	});

}


function vimeo_player_loaded(swf_id) {
	var moogaloop = document.getElementById('videoPlayerObject');
	moogaloop.api_addEventListener('onPlay', 'vimeo_on_play');	
	moogaloop.api_addEventListener('onFinish', 'vimeo_on_finish');	
	moogaloop.api_addEventListener('onPause',    'vimeo_on_finish');
	setThePlayerSize('#videoPlayerObject');
				
	$(window).resize(function() {
		setThePlayerSize('#videoPlayerObject');
	});
	
	if(is_firefox_below_4()){
		$('#value-taglines li').click(function(){
			try{
				moogaloop.api_play();
			}catch(err){
				var a;
			}
		});
	}
	
	if(is_firefox_below_4() && videoPlaying){
		moogaloop.api_play();
	}
}

function vimeo_on_play(swf_id) {
	$('#wrapper, #bg').fadeOut(800);
	$('#value-taglines, #bg').hide();
	$('#background').css('backgroundImage', 'none');
	$('#background').css('backgroundColor', 'transparent');
	$('#play_button').hide();
	videoPlaying = true;

//	$('video').show();
}

function vimeo_on_finish(swf_id) {
	$('#wrapper').fadeIn(800);
	$('#value-taglines').show();
	$('#value-taglines li:not(:first)').css('display', 'none');
//	$('#background').css('backgroundImage', 'url("/images/bg-1440.jpg")');
//	$('#background').css('backgroundColor', '#8eb0e0');
	if ( $.browser.msie && parseInt($.browser.version, 10) < 9 ) {
	 var a;
	} else {
	  if(!is_firefox_below_4()){
	  $('#play_button').show();
	  }
	}
	
//	$('video').hide();
	videoPlaying = false;
}

function video_playing(e) {
	if(!videoInProgress) {
	$('#progress').hide();
	}
}

function video_in_progress(e) {
	if(e.lengthComputable && e.loaded && e.total) {
		if(e.loaded > e.total/4) { videoInProgress = false; }
	} else {
		videoInProgress = false;
	}
}

function playVideo() {
	var player = $('#videoPlayerObject')[0];
	var HTML5_video = document.getElementById('html5_video');

	if(videoPlaying) {
		try {
		HTML5_video.pause();
		} catch(err) { var a;}
		try {
		player.api_pause();
		} catch(err) { var a; }
	} else {
		try {
		HTML5_video.play();
		} catch(err) { var a; }
		try {
			if(is_firefox_below_4()) {
				$('#video_player').css('display','block');
				videoPlaying = true;
				$('#video_player').css('z-index','0');
				$('#background').prepend('<div id="vimeo_player" style="position:absolute;"></div>');
				$('#vimeo_player').html($('#video_player'));
			} else {
				player.api_play();
			}
		} catch(err) { var a; }
	}
}

touchMove = function(event) {
	// Prevent scrolling on this element
	event.preventDefault();
};

function truncate (text, limit, append) {
    if (typeof text !== 'string')
        return '';
    if (typeof append == 'undefined')
        append = '...';
    var parts = text.split(' ');
    if (parts.length > limit) {
        // loop backward through the string
        for (var i = parts.length - 1; i > -1; --i) {
            // if i is over limit, drop this word from the array
            if (i+1 > limit) {
                parts.length = i;
            }
        }
        // add the truncate append text
        parts.push(append);
    }
    // join the array back into a string
    return parts.join(' ');
}

(function () {
    if (!String.prototype.trim) {
        /**
         * Trim whitespace from each end of a String
         * @returns {String} the original String with whitespace removed from each end
         * @example
         * ' foo bar    '.trim(); //'foo bar'
         */
        String.prototype.trim = function trim() {
            return this.toString().replace(/^([\s]*)|([\s]*)$/g, '');
        };
    }     
})();

function empty (mixed_var) {
    // !No description available for empty. @php.js developers: Please update the function summary text file.
    // 
    // version: 1107.2516
    // discuss at: http://phpjs.org/functions/empty
    // +   original by: Philippe Baumann
    // +      input by: Onno Marsman
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: LH
    // +   improved by: Onno Marsman
    // +   improved by: Francesco
    // +   improved by: Marc Jansen
    // +   input by: Stoyan Kyosev (http://www.svest.org/)
    // *     example 1: empty(null);
    // *     returns 1: true
    // *     example 2: empty(undefined);
    // *     returns 2: true
    // *     example 3: empty([]);
    // *     returns 3: true
    // *     example 4: empty({});
    // *     returns 4: true
    // *     example 5: empty({'aFunc' : function () { alert('humpty'); } });
    // *     returns 5: false
    var key;
 
    if (mixed_var === "" || mixed_var === 0 || mixed_var === "0" || mixed_var === null || mixed_var === false || typeof mixed_var === 'undefined') {
        return true;
    }
 
    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }
        return true;
    }
 
    return false;
}
