/********************************************************************************************************
 jquery history navigation functions
********************************************************************************************************/

var url = document.location.toString() ; //url
var e_url = '' ; //edited url
var p = 0 ; //position
var p2 = 0 ;//position 2
p = url.indexOf("//") ;
e_url = url.substring(p+2) ;
p2 = e_url.indexOf("/") ;
var HTTP_SERVER = url.substring(0,p+p2+3);


function scrollToTop(offset){
	var offset = (!offset) ? 0 : offset;
	$('html, body').animate({scrollTop:offset}, 'slow');

}

function ProcessCurrentPage(cp)
{
	var currpage = "";
	var myPath = new Array();
	var myPath = cp.split('/');
	var len = myPath.length;
	var myPage = myPath[len-1];
	//alert(myPage);
	return myPage;
}

function SetCookie( name, value, expires, path, domain, secure )
{
	var today = new Date();
	today.setTime( today.getTime() );
	
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

var cp = document.location.toString() ; //url
var currentPage = ProcessCurrentPage(cp);
SetCookie( 'CurrentPage', currentPage, 30, '/', '', '' );

// global variable to stop the same page from being loaded
var CURRENT_PAGE;

// current username var.  
// if we are already on a user's profile, just refresh the profile content requested
var current_un;

// flag to scroll screen to profile content
var scroll_profile;
function pageload(hash, override) {
	//alert("pageload: " + hash);

	//////////////////////////////////////////////////////////
	// stop if this is the same page, current_un declared above as a global var
	//if(CURRENT_PAGE == hash) return false;
	CURRENT_PAGE = hash;
	//////////////////////////////////////////////////////////



	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// used to break pageload function when modal window refreshes.  
	// #invite_wrapper is located in modalWindow().
	if($('#invite_wrapper').is(':visible') && !override) return false;
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	$("#loading_content").show();
	var offset = 0;
	 scroll_profile = false;
	
	// hash doesnt contain the first # character, load home page
	if(!hash) {
		var get_page = "home.php";
	} else {
		// find if there is more info than just a page to get, otherwise just get the page
		if(hash.indexOf("/")>0) {
			var page = hash.substring(0, hash.indexOf("/"));
			var get = hash.substring(hash.indexOf("/")+1);
			//alert(page+" "+get);
			// replace the '/' with & to create the proper php GET state
			get = get.replace("/", "&");
			//alert(get);
		} else {
			var page = hash;
		}
	
		if(page=='profile') {
			page = 'profile/'+page;
			//alert(page);
			// offset used to scroll screen to content
			//offset = 145;
			var values = get.split("&");
			var username = values[0];
			//alert(values[0]+"  "+values[1]);
			// if we are not visiting the default status page, get profile page 
			if(values[1]) {
				// set flag to scroll to profile content
				//scroll_profile = true;
				scroll_profile = false;
				var variables = values[1].split("/");
				//alert(variables);
				// profile tab 
				
				var tab = variables[0];
				var profile_page = 'profile/'+variables[0]+".php?username="+username;
				//var profile_navigation = 'profile/'+variables[0]+"_navigation.php?username="+username;
				var profile_navigation = 'profile/side_nav_ajax.php?username='+username;
				//alert(profile_page);
				for(var i=0; i<variables.length; i++){
					if ( variables[i].indexOf('=') > 0 )
					{
						delim = '&';	
					}else{
						delim = "&pg=";	
					}
					profile_page += delim+variables[i];
					profile_navigation += delim+variables[i];
					if (variables[i] == "dashboard")
						statusClasses();
					if (variables[i] == "edit-account")
						accountClasses();
				}
			} else {
				// default state of profile page
				var tab = "status";
				profile_page = "profile/status.php?username="+username+"&pg="+CURRENT_PAGE;
				//profile_navigation = "profile/status_navigation.php?username="+username+"&pg="+CURRENT_PAGE;
				profile_navigation = "profile/side_nav_ajax.php?username="+username+"&pg="+CURRENT_PAGE;
			}
			
			// load user followers
			userFollowers(username);
			
			var get_page = page+".php?username="+username+"&pg="+CURRENT_PAGE;
			//alert(get_page);

		} else if(get) {
			var get_page = page+".php?"+get;
			$(".main_left").animate({width: "520px"}, 500 );
		} else {
			var get_page = page+".php";
			$(".main_left").animate({width: "520px"}, 500 );
		}
	}
	
	//alert("get page: "+get_page+"  page:");
	// change ad on right site
	changeAds();	
	
	//scrollToTop(offset);
	homePage(page);

	if(username) {
		// get page header info by page
		getHeaderInfo('profile', username);
		
		if(username == current_un) {
			profilePage(profile_page, profile_navigation);	
			// hide page loading gif
			$("#loading_content").fadeOut();
		} else {
			scrollToTop(offset);
			 scroll_profile = false;
			 //alert(get_page);
			$(".main_left").animate({opacity:0}, function(){
				$.get(get_page, function(response){

					$(".main_left").html(response);
					$(".main_left").animate({opacity:1}, function(){

						// Google Analytics page tracker
						googleAnalytics(get_page);

						// set css of current tab on profile being loaded
						$('.tab-'+tab).addClass('profile_tab_wrapper_active');
						
						// set current profile page
						current_un = username;
						
						// set profile tab rollover and click css
						profileTabs();
						
						// load profile page
						$("#profile_content").fadeOut('fast', function(){
							profilePage(profile_page, profile_navigation);
							profileClasses();
							accountClasses();
						});
						$("#profile_navigation").fadeOut('fast', function(){
							profilePage(profile_page, profile_navigation);
						});
					});
				}, "html");
				
				// hide page loading gif
				$("#loading_content").fadeOut();
			});
		}
		
	} else {
		// get page header info by page
		getHeaderInfo(page);
		
		scrollToTop();
		current_un = '';
		$(".main_left").animate({opacity:0}, function(){
			$.get(get_page, function(response){
				//alert(response);
									 
				$(".main_left").html(response);
				
				$(".main_left").animate({opacity:1}, function(){

					// Google Analytics page tracker
					googleAnalytics(get_page);

					// reload global javascript for new content
					globalClasses();
					
					// set up shareThis button
					if(page == 'buzz' || page == 'buzz-archive') {
						$('.share_this').each(function(){
							var share = $(this).attr('rel');
							share = share.split("||");
							//alert(share[1]);
							var id = $(this).attr('id')+"_obj";
							var thisobj = SHARETHIS.addEntry({
							title:share[1], url:share[0]
							}, {button:false})
							thisobj.attachButton(document.getElementById(id));	
							SHARETHIS.onReady();
						});
						
					}									  
				});

				// load javascript on selected page
				if(page == 'home')
					tagLineLinks();
				else if(page.search(/signup/)> -1)
					signupClasses();
				else if(page == 'buzz') 
					setNewsVideos();
				else if(page.search(/browse/)> -1 || page.search(/search/)> -1) {
					searchPlayerClasses();

					////////////////////////////////////////////////////////////////////////////////////////	
					// browse_genre drop down menu		
					$(".dropdown dt a").click(function() {
						$(".dropdown dd div").toggle();
					});
								
					$(".dropdown dd ul li a").click(function() {
						var text = $(this).html();
						$(".dropdown dt a span").html(text);
						$(".dropdown dd div").hide();
					});
						 
		
					$(document).bind('click', function(e) {
						var $clicked = $(e.target);
						if (! $clicked.parents().hasClass("dropdown"))
							$(".dropdown dd div").hide();
					});
					// END browse_genre drop down menu		
					////////////////////////////////////////////////////////////////////////////////////////	
				}
					
				// hide page loading gif
				$("#loading_content").fadeOut();
			}, "html");
		});
	}	
}


/*********************************************************************
** LOAD PROFILE FOLLOWERS **
*********************************************************************/
function userFollowers(username) {
	$.ajax({
		type: "GET",
		url: HTTP_SERVER+"profile/followers.php",
		data: "username="+username,
		/*beforeSend: function(x) {
		 	if(x && x.overrideMimeType) {
		  		x.overrideMimeType("application/j-son;charset=UTF-8");
		 	}
		},*/
		dataType:'html',
		success: function(msg){
			//if(parseInt(msg.status)==1) {
				$('#followers').html(msg).fadeIn('slow');
			//}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			alert('error: ' + XMLHttpRequest.responseText);	
		}
	});	// end ajax	
}


function profilePage(page, navigation) {
	// alert(navigation);
	$(".main_right").css("display","none");
	$(".main_left").animate({width: "700px"}, 500 );
	$("#loading_profile").show();
	
	$.get(page, function(response){
		$('#profile_content').html(response).fadeIn('slow');
			statusClasses();						 
		// Google Analytics page tracker
		googleAnalytics(page);
		
		//alert(response);
		// hide profile loading gif
		$("#loading_profile").fadeOut();
		
		if(scroll_profile==true) {
			var offset = $('#profile_content').offset();
			scrollToTop(offset.top-45);		
		}
		// initialize classes
		globalProfileClasses();
		globalClasses();
		
		// get content page and call needed classes
		var content_page = page.replace('profile/', '').split(".");
		// alert(content_page);
		if(content_page[0].search(/status/)> -1) 
			statusClasses();
		else if(content_page[0].search(/blog/)> -1)
			blogClasses();
		else if (content_page[0].search(/event-create/)> -1) {
			$(document).ready(function(){
						$("#datepicker").datepicker({
							changeMonth: true,
							changeYear: true,
							dateFormat: "DD - MM d, yy",
							maxDate: '+4y',
							minDate: '0'
						});
				});
		} else if(content_page[0].search(/event/)> -1)
			eventClasses();
		else if(content_page[0].search(/music/)> -1)
			musicClasses();
		else if(content_page[0].search(/video/)> -1)
			videoClasses();
		else if(content_page[0].search(/details/)> -1)
			accountClasses();
		else if(content_page[0].search(/photo/)> -1)
			photoClasses();
		else if(content_page[0].search(/music/)> -1)
			musicClasses();
		else if(content_page[0].search(/account/)> -1)
			accountClasses();

	});
	//alert(navigation);
	$.get(navigation, function(response){
		$('#profile_navigation').html(response).fadeIn('slow');
	});
	
}

function homePage(page){
	//alert(page);
	if ( page.indexOf("profile", 0) < 0 )
		$("#left_side_followers").hide();
	if(page == 'home' || page==''){
		$(".main_left").animate({marginTop: "6px"}, 500 );
		$("#left_main_wrapper").animate({marginTop: "6px"}, 500, function(){
			$("#hero_container").fadeIn();		
		});
		$(".main_right").css('display','none');
		$(".main_right:hidden:first").fadeIn('slow');
		$(".main_right").animate({marginTop: "-284px"}, 0 );
	} else {
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// hide hero and move the music player and center div up  if hero is visible
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		if($("#hero_container").is(":visible")){
			$("#hero_container").fadeOut('fast', function(){
				$(".main_left").animate({marginTop: "0px"}, 500 );	
				$("#left_main_wrapper").animate({marginTop: "0px"}, 500 );
				$(".main_right").animate({marginTop: "0px"}, 0 );
			});	
		}
	}
}


function ajaxNav(){
	var hash = this.href;
	hash = hash.replace(/^.*#/, '');
	// moves to a new page. 
	// pageload is called at once. 
	// hash dont contain "#", "?"
	$.historyLoad(hash);
	return false;
}

function globalClasses(){
	$("a[rel='history']").bind('click', ajaxNav);
	musicClasses();
	
	
	
	
	function findimg()
	{
	 var imgs,i;
	// loop through all images of the document
	 imgs=document.getElementsByTagName('img');
	 for(i=0;i<imgs.length;i++)
	 {
	// test if the class 'roll' exists
	  if(/rollover_image/.test(imgs[i].className))
	  {
	// add the function roll to the image onmouseover and onmouseout and send
	// the image itself as an object
	   imgs[i].onmouseover=function(){roll(this);};
	   imgs[i].onmouseout=function(){roll(this);};
	  }
	 }
	}
	function roll(o)
	{
	 var src,ftype,newsrc;
	// get the src of the image, and find out the file extension
	 src = o.src;
	 ftype = src.substring(src.lastIndexOf('.'), src.length);
	// check if the src already has an _on and delete it, if that is the case 
	 if(/-over/.test(src))
	 {
	  newsrc = src.replace('-over','');
	 }else{
	// else, add the _on to the src 
	  newsrc = src.replace(ftype, '-over'+ftype);
	 }
	 o.src=newsrc;
	}
	findimg()

	
	
	
	
	
	
	
	
/*$('img.rollover_image').each(function(){
    var t=$(this);
    var src1= t.attr('src'); // initial src
	var http_link = 'http://dev.likezebra.com/images';
    var newSrc = src1.substring(src1.lastIndexOf('/'), src1.lastIndexOf('.')); // let's get file name without extension
    t.hover(function(){
        $(this).attr('src', http_link+newSrc+ '-over.' + /[^.]+$/.exec(src1)); //last part is for extension 
		//alert(http_link+newSrc);
    }, function(){
        $(this).attr('src', http_link+newSrc + '.' + /[^.]+$/.exec(src1)); //removing '-over' from the name
    });
});
*/
	
	
	
	
	
	/*$('.rollover_image').each(function() {

		// preload over images
		var src = $(this).attr('src');
		var ext = src.substring(src.length-4);
		var over_src = src.replace(ext, "-over"+ext);
		//var cache_image = document.createElement('img');
		//cache_image.src = over_src;

		// rollover image
		$(this).hover(function() {
			$(this).attr('src', over_src);
			alert(over_src);
		}, function() {
			$(this).attr('src', src);
		});
		
	});*/
	
}


function changeAds(){

	if(CURRENT_PAGE=='home'){
		$("#myspace_vid_ad").show();
		$("#foundin_ad").show();
		
		$('#site_right_ad').fadeOut(function(){
			$('#not_home_hide').show();
			$('#site_right_likezebra').fadeIn();
		});
	} else if(CURRENT_PAGE=='signup' || CURRENT_PAGE=='signup-fan'){
		$('#site_right_ad').fadeOut(function(){
			$('#not_home_hide').hide();
			$('#site_right_likezebra').fadeIn();		
			
			if(CURRENT_PAGE=='signup') {
				$("#myspace_vid_ad").show();
				$("#foundin_ad").hide();
			} else {
				$("#myspace_vid_ad").hide();
				$("#foundin_ad").show();
			}
				
		});
	} else {
		$('#site_right_likezebra').fadeOut(function() {
			$('#site_right_ad').fadeIn();							   
			$('#large_ad').attr('src', 'large_square.php');
		});
	}
}


function getHeaderInfo(page, username) {
	//alert(page+" "+username);
	if(!page)
		var page = 'Home'
		
	if(!username)
		username = '';

	// get header info and insert into tags
	$.ajax({
		type: "POST",
		url: "header_info.php",
		data: 'page='+page+'&username='+username,
		dataType: 'json',
		success: function(msg){			
			//alert(msg);
			$('title').html(msg.title);
			$('meta[name="keywords"]').attr('content',msg.keywords);
			$('meta[name="description"]').attr('content', msg.description);
			//alert(msg.title+" : title : "+$('title').html());
			//alert(msg.keywords+" : Keywords : "+$('meta[name="keywords"]').attr('content'));
			//alert(msg.description+" : description : "+$('meta[name="description"]').attr('content'));

		}
	});
	
}

// Google Analytics page tracker
function googleAnalytics(page){
//	pageTracker._trackPageview(page);
}


/********************************************************************************************************
 END jquery history navigation functions
********************************************************************************************************/