/***
	Generic JavaScript functions for homepage
***/

var promoMiliseconds = 10000;
var precacheImageArray = ['images/homepage/promo/get-started.png', 'images/homepage/promo/get-started-over.png'];
var curPromo = 1;
var curQuote = 1;
var newQLeft = 0;
var promoTimeout = false;
var init = false;
var videoPlaying = false;

function nextPromo() {
	if (videoPlaying) { return; }
	if (!jQuery("#promo2").length) { return; }
	if (!init) {
        	init = true;
		for(idNo=2;idNo<=4;idNo++) {
			jQuery("#promo"+idNo).hide();
		}
	} else {
		idNo = (curPromo==4) ? 1 : (curPromo==3) ? 4 : (curPromo==2) ? 3 : (curPromo==1) ? 2 : 0;
		jQuery("#promo"+curPromo).fadeOut(600, function(){
        	jQuery("#prmNav"+curPromo).removeClass("on");
		jQuery("#promo"+idNo).fadeIn(600);
        	jQuery("#prmNav"+idNo).addClass("on");
        	curPromo = idNo;
    	})    
    }
    promoTimeout = setTimeout('nextPromo()', promoMiliseconds);
}

var MemberCounter = function($tie, $speed) {
	var tie = $tie,
		count = tie.html(),
		speed = $speed || 10000,
		nums = [],
		height = 0;

	function Init() {
		// ok make the count a number
		count = parseInt(count.replace(/,/g, ''));
		// construct the crazy html
		BuildHTML();
		HandleRender();
		// now fire the tick
		setTimeout(HandleTick, Math.random()*speed);
	}

	function BuildHTML() {
		tie.empty();
		var commas = count.toString().length;
		for (var i = 0, length = commas; i < length; i++) {
			var html = '<span class="counter-number">';
			for (var u = 0; u < 10; u++) {
				html += '<span class="counter-item">'+u+'</span>';
			}
			html += '<span class="counter-item">0</span>';
			var num = $(html+'</span>').appendTo(tie).css('top', 0);
			nums.push(num);
			if (commas % 3 == 1 && i+1 < length) {
				$('<span class="counter-number counter-comma">,</span>').appendTo(tie);
			}
			commas--;
			if (height == 0) {
				height = jQuery('span:first-child', num).outerHeight();
			}
		}
	}

	function HandleRender() {
		var bits = count.toString().split('');
		for (var i = 0, length = bits.length; i < length; i++) {
			var position = 0-parseInt(bits[i])*height,
				end = false,
				top = parseInt(nums[i].css('top'));
			if (position == 0 && top != 0) {
				position = 0-(10*height);
				end = true;
			}
			if (position != top) {
				nums[i].data('end', end).addClass('counter-glow').animate({
					'top' : position
				}, 200, 'swing', function() {
					var item = jQuery(this);
					if (item.data('end')) {
						item.css('top', 0);
					}
					item.removeClass('counter-glow');
				});
			}
		}
	}

	function HandleTick() {
		// increment the count
		count++;
		// render
		HandleRender();
		// now fire the tick
		setTimeout(HandleTick, Math.random()*speed);
	}

	Init();
};


jQuery(document).ready(function(){
	/* input boxes */

	jQuery("#username").focus(function(){
        if(jQuery("#username").val()=="username"){ jQuery("#username").val(""); }
    })
    jQuery("#username").blur(function(){
        if(jQuery("#username").val()==""){ jQuery("#username").val("username"); }
    })
    jQuery("#password").focus(function(){
        if(jQuery("#password").val()=="password"){
            jQuery("#password").val("");
            if(!jQuery.browser.msie) document.getElementById("password").type = "password";
        }
    })
    jQuery("#password").blur(function(){
        if(jQuery("#password").val()==""){
            if(!jQuery.browser.msie) document.getElementById("password").type = "text";
            jQuery("#password").val("password");
        }
    })
    jQuery("#searchedString").focus(function(){
        if(jQuery("#searchedString").val()=="Search groups"){ jQuery("#searchedString").val(""); }
    })
    jQuery("#searchedString").blur(function(){
        if(jQuery("#searchedString").val()==""){ jQuery("#searchedString").val("Search groups"); }
    })
    jQuery("#emailaddress").focus(function(){
        if(jQuery("#emailaddress").val()=="Enter your email address"){ jQuery("#emailaddress").val(""); }
    })
    jQuery("#emailaddress").blur(function(){
        if(jQuery("#emailaddress").val()==""){ jQuery("#emailaddress").val("Enter your email address"); }
    })
//    jQuery("#password").attr('type','password'); // - not supported by Jquery due to IE error message 
//    document.getElementById("password").type = "password";
    if(!jQuery.browser.msie) if (document.getElementById("password")) document.getElementById("password").type = "text";

    jQuery('.promoNav').html('<ul><li><a id="pausePlay" href="#">pause</a></li><li><a id="prmNav1" class="on" href="#"><span>1</span></a></li><li><a id="prmNav2" class="" href="#"><span>2</span></a></li><li><a id="prmNav3" class="" href="#"><span>3</span></a></li><li><a id="prmNav4" class="" href="#"><span>4</span></a></li></ul>');

/* promo swap */
    jQuery(".promoNav LI A[id!=pausePlay]").click(function(){
        clearTimeout(promoTimeout);
        jQuery("#pausePlay").html("play");
        idNo = jQuery(this).attr("id").substring(6,7);
        //newLeft = (idNo==1) ? 0 : (idNo==2) ? -1000 : (idNo==3) ? -2000 : -3000;
        //jQuery("#promos").animate({ left: newLeft }, function(){
			jQuery("#promo"+curPromo).fadeOut(600, function(){
            jQuery("#prmNav"+curPromo).removeClass("on");
			jQuery("#promo"+idNo).fadeIn(600);
            jQuery("#prmNav"+idNo).addClass("on");
            curPromo = idNo;
        })
        return false;
    })

/* quote shift */
    jQuery("#nextQuote").click(function(){
       jQuery("#quote"+curQuote).fadeOut(250, function(){
            curQuote = (curQuote==numQuotes) ? 1 : curQuote+1;
            jQuery("#quote"+curQuote).fadeIn();
        })
        return false;
    })

/* auto promo swap */
    nextPromo();
	jQuery("#pausePlay").click(function(){
        if( jQuery("#pausePlay").html()=="pause"){
            clearTimeout(promoTimeout);
            jQuery("#pausePlay").html("play");
        } else {
			videoPlaying = false;
            nextPromo();
            jQuery("#pausePlay").html("pause");
        }
        //promoTimeout = setTimeout("nextPromo", 5000);
        return false;
    })

/* auto promo swap */
    if (jQuery('#memberCounter').length) { new MemberCounter(jQuery('#memberCounter')); }

/* precaching */
    jQuery.each(precacheImageArray, function (i, val) {
      jQuery('<img/>').attr('src', mediaHost+val);
    });
    jQuery("#getStarted").hover(
        function() {
            jQuery(this).attr("src",mediaHost+precacheImageArray[1]);
        }, 
        function () {
            jQuery(this).attr("src",mediaHost+precacheImageArray[0]);
        }
    );

/**
 * Add target="_blank" to all links with rel="external"
 * Allows opening links in new window while preserving valid XHTML
 */
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
		{
			anchor.target = "_blank";
		}
	}

});

if (jQuery("#ytapiplayer") && (typeof(swfobject) != 'undefined')) {
	var params = { allowScriptAccess: "always", wmode: 'opaque' };
	var atts = { id: "myytplayer" };
	swfobject.embedSWF("http://www.youtube.com/v/G1523PltSjA?enablejsapi=1&playerapiid=ytplayer", "ytapiplayer", "410", "250", "8", null, null, params, atts);
}

function onYouTubePlayerReady(playerId) {
  ytplayer = document.getElementById("myytplayer");
  ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

function onytplayerStateChange(state) {
	switch (state) {
		case 1: //playing
		case 3: //buffering
			// Video has begun playing/buffering
			promoControl('stop');
            jQuery("#pausePlay").html("play");
			break;
		case -1: //unstarted
		//case 2: //paused (when manually seeking through the video the state changes to paused, so this starts the slideshow again.)
		case 0: //ended
			// Video has been paused/ended
			promoControl('play');
            jQuery("#pausePlay").html("play");
			break;
	}
}

function promoControl(method) { 
	switch(method) { 
		case 'play':
			videoPlaying = false;
			setTimeout("nextPromo()", 2000);

			break;
		case 'stop':
			videoPlaying = true;
			break;
	}
}

