/*
 * yo yo yo I'm CORE.JS
 * you jive with me I'll make you a mess
 * sync your code and commit your lines 
 * comment your functions and spit ill rhymes
 */

/*
 ** 4 different Menus <> For user testing
 */

var mainPageTitle = "";



$.ajaxSetup({
	  error: function(jqXHR, textStatus, errorThrown){
		  console.log(jqXHR);
		  //console.log(errorThrown);
		  if(jqXHR['status'] == 404){
			  notification("Page Not Found");
		  } else {
			  
			  if (jqXHR['status'] == 200){}else{
				 
				  notification(jqXHR['status']+" ERROR");
				  
			  }
			  
			 
		  }
	  }
	});

var loadingCount = 0;

function setLoading(){
	loadingCount += 1;
	$('body').css('cursor','wait');
}
function stopLoading(){
	loadingCount -= 1;
	if (loadingCount == 0){
		$('body').css('cursor','auto');
	}
}

if(console==undefined){
 //alert('sdsd');
 
 var console = {
		 log: function () {
			 //do nothing
		 }
 }
 
}
$('#menu0 li a').live('click', function(){
	$('#hostParty').dialog('close');
});
$('#menuNames li').live('click', function() {
	$('#menuNames li').removeClass('activeMenu');
	$(this).addClass('activeMenu');
	$('.mChangeColor ul').hide();
	$('#menu' + $(this).index() + ' ul').show();
});

$('#menuColors li').live('click', function() {
	$('.mChangeColor div').hide();
	$('.mChangeColor div.' + $(this).attr('class') + '').show();
	
	$('.mChangeColor').removeClass('wcs ocs gcs')
	switch ($(this).attr('class')) {
		case 'white': color = '#fff'; $('.mChangeColor').addClass('wcs');
		break;
		case 'orange': color = '#ffba00';  $('.mChangeColor').addClass('ocs');
		break;
		case 'green': color = '#add136'; $('.mChangeColor').addClass('gcs');
		break;
		default: 'def';
	}
	$('.mChangeColor a').css('color', color);
});

$('.mChangeColor li').live('mouseenter mouseleave', function(e) {
	if (e.type == 'mouseenter') {
		var hoverGreen = '';
		var hoverWhite = '';
		if ($(this).parent().parent().attr('id') == 'menu3' || $(this).parent().parent().attr('id') == 'menu4') {
			hoverGreen = 'hoverGreenB';
			hoverWhite = 'hoverWhiteB';
		} 
		else {
			hoverGreen = 'hoverGreenA';
			hoverWhite = 'hoverWhiteA';
		}
		
		if ($(this).parent().parent().hasClass('wcs') == true || $(this).parent().parent().hasClass('ocs') == true) {			
			$(this).addClass(hoverGreen);
		}
		else {
			$(this).addClass(hoverWhite);
		}
		
	}
	else { 
		$(this).removeClass('hoverGreenA hoverWhiteA hoverGreenB hoverWhiteB');
	}
});

function newUpdate(){
	if ($("#updatesPanelWrap").css("display") != "none"){
		$('.updatesTabs').tabs("load", 0);
	}
	else{
		$.getJSON('index.php?r=mystuff/getunreadtotal', function (data) {
			if (data.count > 0) {
				$('.updatesTabs').tabs("load", 0);
				$('#setArrow .orangeBox').html(data.count);
				$('#setArrow .orangeBox').show();
				$('#setArrow .orangeBox').fadeTo('slow', 0.5).fadeTo('slow', 1.0).fadeTo('slow', 0.5).fadeTo('slow', 1.0);
			}
		});
	}
}
//#######################################



/*
 * * LOGIN FORM
 */
$('#headerLogin').live('click', function() {
	if ($(this).hasClass('greyBtn') == false) {
		$('#subNav').slideDown(250);
		$(this).removeClass().addClass('greyBtn greyGrad rounded').html('cancel');
		$('#YumUserLogin_username').focus();
	}
	else {
		$('#subNav').slideUp(250);
		$(this).removeClass().addClass('greenBtn greenGrad rounded').html('login');
	}
});

$("#subNav form").live('submit',function(e){
	e.preventDefault();
	login($('#YumUserLogin_username').val(),$('#YumUserLogin_password').val(),$('#snRememberForgot .tickBox').is(".checked"));
});

function login(username,password,rememberMe){
	href = $("#subNav form").attr('action');
	post_data = "YumUserLogin[password]="+password+"&YumUserLogin[username]="+username;
	
	$.ajax({
		url:href,
		type:"post",
		data: post_data,
		success: function(data){
			if(data == "error") {
				notification('Wrong email or password, please try again');
			}else{
				$('#subNav').slideUp(500);
				$('.vTextField').trigger('blur');
				$('#iContent').animate({marginTop:"0px"},500);
				$('body').append(data);
				$('body').addClass('loggedIn').removeClass("guest");
				setScrolls();
				set_resize_function();
				notification('You are logged in.');
				localStorage.clear();
				
				if (window.location.hash.match('stage')){
					$(document).trigger('join_shoutout', {event_code: "stage"});
				}
			
				redirectRegLogPage();
				refresh_iContent();
				setTimeout(set_chat_drops,1000);
				$(".chatPanel").tabs({
					   show: function(event, ui) { chat_scroll_bottom(); }
				});			
			}
		},
		error: function(error){
			console.log(error);
		}
	});
}

$('.logout').live('click',function(event){
	event.preventDefault();
	
	$.ajax({
		url: "index.php?r=mystuff/logout",
		success: function(data){
			$("#chatPanelWrap,#friendsOnline,#playlistPanelWrap,#updatesPanelWrap").remove();
			if ($('#subNav').length>0){
				$('#subNav').slideDown(0);
			} else {
				
			}
			
			notification('You are now logged out, come back soon!');
			chat.disconnect();
			$('body').removeClass('loggedIn').addClass("guest");
			location.reload();
		},
		error: function(error){
			console.log(error);
		}
	});
	$('#YumUserLogin_password').attr('value','');
})
//###########################################################################################



/*
 * *INDEX
 */
$('input[name$="messageNote"]').live('click', function(){
	
	$.ajax({
		url: $(this).parents('form').attr('action'),
		type: "POST",
		data: "MessageNote[to_user_id]="+$(this).siblings('input[name="MessageNote[to_user_id]"]').val()+'&MessageNote[message]='+$(this).siblings('textarea[name="MessageNote[message]"]').val(),
		success: function(data){
			
			// fix me : this is shit, my bad, dave
			
			//$(data).appendTo('body').tabs();
			//$(this).parents('.idCard').remove();
			$('textarea[name="MessageNote[message]"]').val("");
			notification('Your message was sent');
			$('.updatesTabs').tabs("load", 0);
		}
	})
	//alert("MessageNote[to_user_id]="+$(this).siblings('input[name="MessageNote[to_user_id]"]').val()+'&MessageNote[message]='+$(this).siblings('textarea[name="MessageNote[message]"]').val());
	return false;
})

$('#updates_tab_1 .ui-icon.ui-icon-close').live('click',function(){
	closeBtn = $(this);
	$('<p>Are you sure you want to delete this message?</p>').yuriBox({
		buttons: {
			Delete: function(){
				$(this).dialog("close");
				$.ajax({
					//type: 'POST',
					url : 'index.php?r=mystuff/deletemessage&deleteMessage='+closeBtn.parent('.message').data('message_id'),
					success: function(data){
						closeBtn.parents('.message').remove();
						notification("Message Deleted");
						
					}
				});
			},
			Cancel: function(){
				$(this).dialog("close");
			}
		}
	})
})

/*
$('#friendsList .ui-icon.ui-icon-close').live('click',function(){
	closeBtn = $(this);
	$.ajax({
		url : 'index.php?r=mystuff/deleteMessage&deleteMessage='+closeBtn.siblings('.chatDragger').data('user_id'),
		success: function(data){
			closeBtn.parent().remove();
			//notification(closeBtn.siblings('.chatDragger').data('user_name')+' has been deleted from your friend list');
		}
	});
	
})
*/

$('#friendsList .ui-icon.ui-icon-close').live('click',function(){
	closeBtn = $(this);
	$.ajax({
		url : 'index.php?r=mystuff/deleteFriend&deleteProfile='+closeBtn.siblings('.chatDragger').data('user_id'),
		success: function(data){
			closeBtn.parent().remove();
			notification(closeBtn.siblings('.chatDragger').data('user_name')+' has been deleted from your friend list');
		}
	});
	
})

$('a.replyToMessage').live('click', function(){
	$('.idCard[data-user_jid="'+$(this).parents('.chatDragger').data('user_jid')+'"]').remove();
	$.ajax({
		url: $(this).attr('href'),
		success: function(data){
			$(data).appendTo('body').tabs();
		}
	})
	return false;
})

$('button.replyToMessage').live('click', function(){
	$('.idCard[data-user_jid="'+$(this).parents('.chatDragger').data('user_jid')+'"]').remove();
	$.ajax({
		url: $(this).data('href'),
		success: function(data){
			$(data).appendTo('body').tabs();
		}
	})
	return false;
})

$('.sCommentsAdd').live('click', function(){
	mpq.track("add_friend");

	$.ajax({
		url: $(this).attr('href'),
		success: function(data){			
			notification("Request was sent!");
			$(this).hide();
		}
	})	
	return false;
})

$('#addVOFriend').live('click', function(){
	mpq.track("add_friend");
	$('.addAsFriend').text('Pending');
	if ( $(this).parents(".idCard").length == 0 )
	{
		$(this).parent().parent().css('display', 'none');
		$.ajax({
			url: $(this).attr('href'),
			success: function(data){
			//$(data).appendTo('body').tabs();			
			notification("Request was sent!");
			}
		});
	}
	return false;
})

$('#addFBFriend').live('click', function(){
	mpq.track("add_friend");
	$('.addAsFriend').text('Pending');
	if ( $(this).parents(".idCard").length == 0 )
		$(this).parent().parent().css('display', 'none');
	
	$.ajax({
		url: $(this).attr('href'),
		dataType: "json",
		success: function(data){		    	
        	
	        if (data['status'] == 'OK') {      		
	     		
	     		// POST TO THE WALL	    		
	            var params = {};
	            friend_id = data['fbid'];
	            params['message'] = ' wants you to join them on VenueOne.com';
	            params['name'] = 'VenueOne';
	            params['description'] = 'Watch exclusive live concerts and login to connect with friends';
	            
	            params['link'] = data['link'];        
	            params['picture'] = 'http://venueone.com/images/facebook-venueone-logo2.jpeg';
	            params['caption'] = 'The Original Online Venue';
	              
	            FB.api('/' + friend_id + '/feed', 'post', params, function(response) {
	              if (!response || response.error) {
						notification("Request wasnt sent!");
	              } else {
	            	  	notification(data['message']);
	              }
	            });
	        		     		
	       		        
			}else{				
					
				notification("Error");
					
				
			}
    	},
    	
	    error: function(error){
	    	notification('Request was not send.');	        	
	    }
    	
	})	
	return false;
})

$('.acceptFriend').live('click', function(){
	$(this).parent().parent().css('display', 'none');
	console.log($(this).attr('href'));
	$.ajax({
		url: $(this).attr('href'),
		success: function(data){
			notification("Request was accepted!");
		}
	})	
	return false;
})

$('.declineFriend').live('click', function(){
	$(this).parent().parent().css('display', 'none');
	newUpdate();
	
	$.ajax({
		url: $(this).attr('href'),
		success: function(data){
			$(data).appendTo('body').tabs();			
			notification("Request was declined!");
		}
	})	
	return false;
})

$('.acceptParty').live('click', function(){
	mpq.track("accept_party_invitation");
	$(this).parent().parent().parent().css('display', 'none');
	
	$.ajax({
		url: $(this).attr('href'),
		success: function(data){
			$(data).appendTo('body').tabs();			
			notification("Party Invite was accepted!");
		}
	})	
	return false;
})

$('.declineParty').live('click', function(){
	$(this).parent().parent().parent().css('display', 'none');
	notification("Party Invite was declined!");
	return false;
})
//#########################################


//########## Check Boxes ##########
$('.tickBox').live('click', function() {
	if ($(this).hasClass('checked') == false) {
		$(this).addClass('checked');
	}
	else {
		$(this).removeClass('checked');
	}
});
//#######################################


//######### Text Fields / Text Areas functions and validation ##########
$('span.tfSpan').live('click', function() {
	$(this).prev().focus();
});

//show Tooltip if needed and chane TF/TA to on focus style
$('.vTextField').live('focus', function () {
	$(this).next('span').css('color','#919191');
	if ($(this).data('tooltip')) {
		if($(this).next().css('display') == 'none') {
			tooltip($(this), $(this).data('toolname'), $(this).data('tooltip'));
		}
	}
});

//return to defalut style nad return tfSpan or to filled text field/textarea style 
$('.vTextField').live('blur', function () {
	if($(this).val() == '') {
		$(this).next('span').css('color','#363535');
		$(this).next('span').show();
	}
});

//hide tfSpan and show tooltip
$('.vTextField').live('keydown', function (e) {
	$(this).next('span').hide();
	if ($(this).data('tooltip')) {
		tooltip($(this), $(this).data('toolname'), $(this).data('tooltip'));
	}
});
//#####################################################################



//########## TOOLTIP ##########
$("#friendsOnline .chatDragger, #chatPanelWrap .chatDragger").live('mouseenter', function(){
	tooltip($(this), $(this).data("user_name"), "tooltip");
}).live('mouseleave', function(){
	$('.tooltip').remove();
})
$("#friendsOnline .title-friendsOnline").live('mouseenter', function(){
	tooltip($(this), "Drag friend's profile picture to start a chat", "tooltip");
}).live('mouseleave', function(){
	$('.tooltip').remove();
})

$('#youtubeContent li').live('mouseenter', function() {
	tooltip($(this), $(this).data('youtube-title'), 'tooltip', 'top');
}).live('mouseleave', function() {
	$('.tooltip').remove();
});

/*$('.trioTooltip').live('mouseenter', function() {
	tooltip($(this), $(this).data('title'), 'tooltip', 'auto');
}).live('mouseleave', function() {
	$('.tooltip').remove();
});*/


//Tooltips and Errors(errortip) function
var tpIsShown = false;
function tooltip(selector, text, type, position) {
	if (tpIsShown == false) {
		$('body').append('<div class="' + type + '">' + text + '<div class="ttArrowBTop tooltipArrowBorder"></div><div class="ttArrowTop tooltipArrow"></div></div>');
		
		var tooltipHeight = $('.' + type + '').height() + 14; //tooltip height pluss tooltip padding
		pos = selector.offset();
		$('.' + type + '').css('left',pos.left);
		
		if (position == 'top') {
			$('.tooltipArrowBorder').removeClass('ttArrowBTop').addClass('ttReverseArrowB');
			$('.tooltipArrow').removeClass('ttArrowTop').addClass('ttReverseArrow');
			$('.' + type + '').css('top', pos.top - tooltipHeight - 13); //13 is hight of tooltip arrow
		}
		
		else if (position == 'right') {
			
		}
		
		else {
			//check if there enough space under te element to show tooltip, if not enough than show the tooltip above the element
			if ((pos.top + selector.height()) < $(window).height() - $('#footer').height()) {
				$('.' + type + '').css('top',pos.top + selector.height() + 14);
			}
			else {
				$('.tooltipArrowBorder').removeClass('ttArrowBTop').addClass('ttReverseArrowB');
				$('.tooltipArrow').removeClass('ttArrowTop').addClass('ttReverseArrow');
				$('.' + type + '').css('top', pos.top - tooltipHeight - 13); //13 is hight of tooltip arrow
			}		
		}
			
		//if selector is input than bind a function to its blur event to remove tooltip on blur 
		if (selector.is('input') == true || selector.is('textarea') == true) {
			selector.bind('blur', function() {
				$('.' + type + '').remove();
				tpIsShown = false;
			});
		}
		
		/*TODO
		to add more statement / if buttons, if check boxes and etc
		  
		if (selector.is('div.button') ==  true) {
			-- DO TASK
			tpIsShown = false;
		}
		
		*/
	
		//hide tooltip if scroll
		$('#contentScroll').bind('scroll', function(){
			$('.' + type + '').remove();
			tpIsShown = false;
			$('#contentScroll').unbind('scroll');
		});
	}
}
//################################################################################################

	

//########## Registration functions ##########
$('#snRegisterBtn, #headerJoin, #hpCAllSocialBtn').live('click', function(){
	//$('#subNav').hide();
	//$('#headerLogin').removeClass().addClass('orangeBtn greenGrad rounded').html('login');
	
	$.ajax({  
		url: "index.php?r=registration/registration", //url: "index.php?r=global/registration",
		success: function (data)  { 
			$('#regForm').html(data); 
			$('#regForm').yuriBox({
				title:"Register for free to use<br />VenueOne&acute;s social Features"
				,width:330
				,position: [($('#iContent').offset().left + $('#iContent').width() - 350) + 8, 80 ]
			});
			_gaq.push(['_trackPageview',"Register-Opened"+location.pathname + query_string  + hash]);
		}
	});	
});

$('#snFacebookDate, #facebookLogin, .facebookLogin').live('click',function(){
	$.ajax({
		url: 'index.php?r=global/fbregistration',
		success: function(data){
			$(data).yuriBox({height:360, title:"Sign Up With Facebook"});

			$(data).find("iframe").attr('height','320');
		},
		error: function(error){
			notification("Facebook Connect Error. Do you already have a VenueOne account with the email address connected to your facebook account?")
		}
	})
})

//Registration form validation
$("#regForm form").live('submit',function(e){
	e.preventDefault();
	href = $("#regForm form").attr('action');
	
	//Data Inputs for submission
	//var date;
	//var dateYear = $('#rfYearInput').val();
	//var dateMonth = $('#rfMonthInput').val();
	//var dateDay = $('#rfDayInput').val();
	//var gender = $('#regFormGenre .rbChecked').prev().html().substring(0, 1);
	var newslet = $('#regFormSubscribe .rbChecked').prev().html().substring(0, 1);
	
	//if (dateYear == 'year') { dateYear = '1992'; }
	//if (dateMonth == 'month') { dateMonth = '01'; }
	//if (dateDay == 'day') { dateDay = '01'; }
	
	//date = dateYear + '-' + dateMonth + '-' + dateDay;
	
	//$('#rfDOBData').attr('value',date);
	//$('#rfGenderData').attr('value',gender);
	$('#rfNewsletterData').attr('value',newslet);
	
	post_data = "YumProfile[name]="+$('#YumProfile_name').val() 
    + "&YumProfile[email]="+$('#YumProfile_email').val() 
    + "&YumProfile[subscription]="+$('#rfNewsletterData').val()
    + "&YumProfile[dob]="+"1994-01-01"
    + "&YumProfile[gender]="+"M"
    + "&YumUser[username]="+$('#YumUser_username').val()
    + "&YumUserChangePassword[password]="+$('#YumUserChangePassword_password').val() 
    + "&YumUserChangePassword[verifyPassword]="+$('#YumUserChangePassword_verifyPassword').val();
    
	if ($('#YumUserChangePassword_password').val() != '' && $('#YumProfile_name').val() != ''
			&& $('#YumProfile_email').val() != '' && $('#YumUser_username').val() != '' 
				
		) {
		
		$.ajax({
	        url:href,
	        type:"post",
	        data: post_data,
	        dataType: "json",
	        success: function(data){		    	
		        
		        if (data['status'] == 'OK') { 
		        	
		     		notification(data['message']);
		        	$('#regForm').dialog("close");
		        	login($('#YumProfile_email').val(),$('#YumUserChangePassword_password').val());
		        	$('#regForm').html('');
		        	_gaq.push(['_trackPageview',"Register-Complete"+location.pathname + query_string  + hash]);		     		
		       		        
				}else{
					
					if (data['error_pass']['password'] != undefined) { 
			     		notification(data['error_pass']['password'][0]); 
					} 
			    	
			    	if (data['error_user']['username'] != undefined) { 
			    		notification(data['error_user']['username'][0]);
					}
		   
			    	if (data['error_profile']['email'] != undefined) { 
			    		notification(data['error_profile']['email'][0]);
					}
			 
			        if (data['error_profile']['name'] != undefined) {
			    		notification(data['error_profile']['name'][0]);
					}
				}
	        },
	        error: function(error){
	        	notification('Request was not send.');	        	
	        }
		});
	}
	else {
		notification('Please fill in all fields');
	}
});

function redirectRegLogPage(){
	if(window.location.hash == "#!/dateregister" || window.location.hash == "#!/register"){
		window.location.hash = "#!/";
	}
}




//Activate page form validation
$("#fbActiveFormWrapper form").live('submit',function(e){
	
	e.preventDefault();
	href = $("#fbActiveFormWrapper form").attr('action');
	
	post_data = "fbActiveForm[email]="+$('#fbActiveForm_email').val() + "&fbActiveForm[password]="+$('#fbActiveForm_password').val();
    
	if ($('#fbActiveForm_password').val() != ''	
		) {
		
		$.ajax({
	        url:href,
	        type:"post",
	        data: post_data,
	        dataType: "json",
	        success: function(data){		    	
		        
		        if (data['status'] == 'OK') { 
		        	
		     		notification(data['message']);
		        	$('#regForm').dialog("close");
		        	login($('#fbActiveForm_email').val(),$('#fbActiveForm_password').val());
		        	$('#regForm').html('');
		        	_gaq.push(['_trackPageview',"Register-Complete"+location.pathname + query_string  + hash]);		     		
		       		        
				}else{
					
					/*
					if (data['error_pass']['password'] != undefined) { 
			     		notification(data['error_pass']['password'][0]); 
					} 
					*/
					
					if (data['message'] != undefined){
						
						notification(data['message']);
						
					}else{
			    	
				    	if (data['error_user']['username'] != undefined) { 
				    		notification(data['error_user']['username'][0]);
						}
			   
				    	if (data['error_profile']['email'] != undefined) { 
				    		notification(data['error_profile']['email'][0]);
						}
				 
				        if (data['error_profile']['name'] != undefined) {
				    		notification(data['error_profile']['name'][0]);
						}
					}
				}
	        },
	        error: function(error){
	        	notification('Request was not send.');	        	
	        }
		});		
		
	}
	else {
		notification('Please fill in all fields');
	}
});
//#############################################



/*
 * * DROP DOWN MENUS
 */	
//Drop Menus Text Field on Focus
$('.dropTextField').live('focus', function() {
	$(this).attr('value','').css('font-style','normal');
	$('.dropDown, .dropDownMini').hide();
});

//Drop Menus Text Field on Blur
$('.dropTextField').live('blur', function() {
	if ($(this).val() == '' || parseInt($(this).val()) > $(this).data('defval')) {
		$(this).attr('value',$(this).attr('data-defval')).css('font-style','italic');
	}
	
	if ($(this).hasClass('months') == false) {
		if ($(this).val().length == 1 && $(this).data('defval').toString().length == 2) {
			$(this).attr('value','0' + $(this).val());
		}
		
		if  ($(this).data('defval').toString().length == 4 && ($(this).val().length == 1 || $(this).val().length == 3)) {
			$(this).attr('value',$(this).attr('data-defval'));
		}
		
		else if ($(this).data('defval').toString().length == 4 && $(this).val().length == 2) {
			$(this).attr('value','19' + $(this).val());
		}
	}
	
	else {
		if($(this).val().length < 3) {
			notification('Please type a month (Jan, Feb, Mar and etc)');
			$(this).attr('value',$(this).attr('data-defval')).css('font-style','italic');
		}
		else {
			var months = 'JanFebMarAprMayJunJulAugSepOctNovDec';
			var regExp = new RegExp($(this).val(),'i');
			
			if (months.match(regExp)) {
				$(this).attr('value',months.match(regExp)).css('font-style','italic');
				var datavalue = $('.' + months.match(regExp) + '').attr('data-value');
				$('.monthTransporter').attr('value',datavalue);
			}
			else {
				notification('Please type a month (Jan, Feb, Mar and etc)');
				$(this).attr('value',$(this).attr('data-defval')).css('font-style','italic');
				$('.monthTransporter').attr('value','12');
			}
		}
	}	
});

//Convert Month from Numbers to Letters
function convertMonth() {
	var month = $('.monthTransporter').attr('value');
	var monthName = $('li[data-value=' + month + ']').html(); 
	$('.months').attr('value',monthName);
}

//Check for valid numeric strings
function isNumber(str) {
	if (str.keyCode < 58 && str.keyCode > 47) {
		return str;
	}
	else {
		notification('Please type a number');
		return false;
	}
}

//Check for valid numeric strings
function isLetter(str) {
	if ((str.keyCode < 91 && str.keyCode > 64) || (str.keyCode < 123 && str.keyCode > 96)) {
		return str;
	}
	else {
		notification('Please type a month (Jan, Feb, Mar and etc)');
		return false;
	}
}

//Drop Down Button Click
$('.dropDownBtn, .dropDownBigBtn').live('click', function() {
	$('.dropDown, .dropDownMini').hide();
	
	if ($(this).hasClass('datePickBtn') == false) { 
		if($(this).hasClass('dropOut') == false) {	
			$(this).prev().show();
			$(this).addClass('dropOut');
		}
		else {
			$(this).prev().hide();
			$(this).removeClass('dropOut');
		}
	}
	else {
		if($(this).hasClass('dropOut') == false) {	
			$(this).prev().focus();
			$(this).addClass('dropOut');
		}
		else {
			$(this).removeClass('dropOut');
		}
	}
});

//Drop Down Li Click
$('.dropDown li, .dropDownMini li').live('click', function() {
	var $this = $(this).parent().parent().parent().parent().parent();
	$this.hide();
	$this.next().removeClass('dropOut');
	
	if (!$(this).data('codcou')) {
		$this.prev().attr('value',$(this).html());
	}	
	else if ($(this).data('codcou') ) { 
		$this.prev().attr('value',$(this).html());
		$('#countryCodeTrtans').attr('value',$(this).data('codcou'));
	} 	
	if ($(this).data('value')) {
		$('.monthTransporter').attr('value', $(this).attr('data-value'));
	}
});

//Datepicker Drop Down
$('.hasDatepicker').live('click', function() {
	if($(this).next().hasClass('dropOut') == false) {
		$(this).next().addClass('dropOut');
		$(this).focus();
	}
	else {
		$(this).next().removeClass('dropOut');
		$(this).blur();
	}
});

$('.ui-state-default').live('click', function() {
	$('.datePickBtn').removeClass('dropOut');
});
//##########################################################################################



//########## Radio Button click ##########
$('.radioBtn').live('click', function() {
	$(this).parent().find('.radioBtn').removeClass('rbChecked');
	$(this).addClass('rbChecked');
});
//########################################


//########## Fade out/in page(for lightboxes, registration, popups and etc) ##########
function fadeOutScreen() {
	$('body').append('<div id="fadeScreen"></div>');
	$('#iContentWrap').css('overflow','hidden');
}

function fadeInScreen() {
	$('#fadeScreen').remove();
	$('#iContentWrap').css('overflow','auto');
}
//####################################################################################



/*
 * *HOME PAGE
 */ 
//Featured Gigs Carousel / Animation

//Dave B, don't touch the carousel for now!!!!!
/*
 * Or we could use Nivo slider.. Google it...
 * 
function hpGigsCarousel(show) {
	
	if (typeof gigsCarouselTimeout != "undefined"){
		clearTimeout(gigsCarouselTimeout);
	}
	
	if (typeof show == "undefined"){
		show = $("#featuredGigsUL li").first().next();
		$("#featuredGigsUL li").first().addClass("showing");
	}
	
	
	show.animate({ top: "0%", opacity:1 }, 900,function(){
		$("#featuredGigsUL li.showing").css({top:"100%",opacity:0}).removeClass("showing");
		show.addClass("showing");
	});
	
	
	if (show.next().length > 0){
		gigsCarouselTimeout = setTimeout(function(){hpGigsCarousel(show.next())}, 3000);
		console.log(show.next());
	}else {
		gigsCarouselTimeout = setTimeout(function(){hpGigsCarousel($("#featuredGigsUL li").first())}, 3000);
	}
	
}
*/

function hpGigsCarousel() {
	$('#hpGigsList').animate({ opacity: 1}, 5000, function() {
		if ($('.hpActiveGigImg').parent().index() < 3) {
			$('#featuredGigsUL li:eq(' + $('.hpActiveGigImg').parent().index() + ')').addClass('toOpaq');
			$('.hpActiveGigImg').removeClass('hpActiveGigImg').parent().next().find('img').addClass('hpActiveGigImg');
		}
		else { 
			$('.hpActiveGigImg').removeClass('hpActiveGigImg');
			$('#hpGigsList li:eq(0) img').addClass('hpActiveGigImg');
			$('#featuredGigsUL li:eq(3)').addClass('toOpaq');
		}
		
		$('.toOpaq').fadeOut(1000, function() {
			$('.toOpaq').removeClass('toOpaq');
		});
		
		$('#featuredGigsUL li:eq(' + $('.hpActiveGigImg').parent().index() + ')').fadeIn(1000, function() {
			hpGigsCarousel();
		});
		
	});
}

//On Click
$('#hpGigsList li').live("click",function(){
	$('#hpGigsList').stop();
	$('#hpGigsList li img').removeClass('hpActiveGigImg');
	$(this).find('img').addClass('hpActiveGigImg');
	$('#featuredGigsUL li').hide();
	$('#featuredGigsUL li:eq(' + $(this).index() + ')').show();
});

//Stage info for Home Page
function updateNowPlaying() {
	 $.ajax(
		{
			url: "index.php?r=stage/nowplaying",
			datatype: "JSON",
			success: function(data){
				var now_playing = jQuery.parseJSON(data);
				$('#hpCStageRight').prepend('<img src="' + now_playing.thumbnail + '" />');
				$('#hpCStageRight p').html('');
				$('#hpCStageRight p').html("<span>" + now_playing.artist_name + "</span><br/>");
				$('#hpCStageRight p').append(now_playing.name);
			}
		}
	);
}

//Hover Effect on Parties Home Page
$('.hpCPartiesPName').live('mouseenter mouseleave', function(e) {
	if (e.type == 'mouseenter') {
		$(this).prev().css('border-color','#ffba00');
	}
	else { 
		$(this).prev().css('border-color','#626669');
	}
});
//###############################################################################################


	 
//########## Search function and yuriBox function ##########
$('.ui-widget-overlay').live('click',function(){
	
})

$('.searchFriends').live('keyup',function(){
	$(this).searchList({
		'list':$('#friendsList')
	})
})


$.fn.searchList = function(options){
	var settings = $.extend( {
		'list' : null
	}, options);
	
	if(settings.list == null){
		console.log('Missin list on search for: [bellow]')
		console.log($(this))
	}
	
	needle = this.val();
	regexNeedle = new RegExp(needle,"i");
	
	settings.list.children('li').each(function(){
		if ( $(this).find('*').text().match(regexNeedle) ){
			$(this).css('display','');
		} else {
			$(this).css('display','none');
		}
	})
}

function alert(text){
	$("<p>"+text+"</p>").dialog({title:"Alert!",buttons:{ok:function(){$(this).dialog("close")}}})
}

$.fn.yuriBox = function(options){
	var settings = $.extend( {
		'content'         : this,
		'modal'			: true,
		'title'		: this.attr('title'),
		//'width'		: this.outerWidth(true),
		'width'		: 'auto',
		'resizable' : false,
		'height' : 'auto',
		'buttons': {},
		'draggable':false,
		'position':'center'
	}, options);
	
	console.log(this[0].nodeName);
	
	if (this[0].nodeName == 'A'){
		
		if( settings.width=='auto'){
			settings.width == 800;
		}
		if( settings.height=='auto'){
			settings.height == 500;
		}
		
		settings.content = $('<div style="width:'+settings.width+'px;height:'+settings.height+'px"><iframe src="'+this.attr('href')+'" width="'+settings.width+'" height="'+settings.height+'">Not Allowed</iframe></div>')
		settings.width = 'auto';
		
		console.log(settings.title);
		
		if(settings.title == undefined){
			settings.title = this.attr('href');
		}
		
	}
	
	console.log("$.fn.yuriBox = function("+options+")")
	
	settings.content.dialog({
		modal: settings.modal,
		title: settings.title,
		width: settings.width,
		height: settings.height,
		resizable: settings.resizable,
		buttons: settings.buttons,
		draggable: settings.draggable,
		show: 'blind',
		position: settings.position
	});
	$('.ui-widget-overlay').click('click',function(){
		settings.content.dialog( "close" );
	})
	
}
//###############################################################################################


 
/*
 * *HOST A PARTY
 */
//Open Host a Party window
$('#hostPartyBtn').live('click', function() { showHostParty(); });

//Slide Out Archive/Friend windows
var outComplete = false;
var inComplete = true;

function showHostParty(){
	$.ajax({
		url: 'index.php?r=site/hostparty',
		success: function(data) {
			$('#closeHostFriends').trigger('click');
			hostAF = $("#hostAF");
			$('#hostParty').html(data);
			$('#hostParty').yuriBox({
				title: 'Host a Party',
				draggable:true,
				modal:false
			});
			$('#hostParty').parent().append(hostAF);
			$('#dateTF').datepicker('option', {dateFormat: 'd M yy', minDate: new Date(), defaultDate: new Date() });
		}	
	});
	
}

function slideHostOut(elem) {	
	if (outComplete == false) {
		outComplete = true
		$('#hostParty').parent().animate({ marginLeft: '-=180' }, 700);
		console.log($('#hostAF'));
		$('.slideRightConnector:eq(' + elem + ')').animate({ width: 311, opacity:1 }, 100, function(){
			$('#hostAF').css('borderWidth','1px').animate({ width: '340px' }, 400, function() {
				inComplete = false; 
			});			
		});

	}
}

//Slide back Archive/Friend windows
function slideHostIn() {
	if (inComplete == false) {
		inComplete = true;
		
		$('#hostParty').parent().animate({ marginLeft: '+=180' }, 700);
		$('#hostAF').animate({ width: '0px' }, 400, function() {
			$(this).css('borderWidth','0px')
			outComplete = false;
			$('.slideRightConnector').animate({ width: 298 }, 200);
		});			
	}
}

//Slide Out/In Connection beetwen two Host party and Archive/Friends windows
function slideHostCover($elem, $width, $sec) {
	console.log($elem);
	$('.slideRightConnector').css('width', '298px');
	$('#hostParty .slideRightConnector:eq(' + $elem + ')').animate({ opacity: 1 }, $sec, function() {
		$(this).animate({ width: $width }, 200);
	});
}

//Slide Back Archive/Friends windows
$('#closeHostFriends').live('click', function() { 
	slideHostIn(); 
	$('#hostAF').removeClass('isOut'); 
});

//Slide out Archive Window, Load Artist and change Header 
$('#hostPBrowseArc, #hostPartyYoutubeBtn').live('click', function() {
	$('#hostAF').removeClass('voFOut fbFOut');
	if ($('#hostAF').hasClass('isOut') == false) {
		slideHostOut(0);
		$('#hostAF').addClass('isOut baOut');
	}
	else {
		if ($('#hostAF').hasClass('baOut') == false) {
			$('#hostAF').addClass('baOut');
			slideHostCover(0, 320, 0);
		}
		else if ($('#hostAF').hasClass('baOut') == true) {
			slideHostIn();
			$('#hostAF').removeClass('isOut baOut');
		}
	}
	$('#hostAF h2 span:first-child').html('Select Gigs');
});

//Invite friends from VenueOne li's click and mouse hover
$('.hostVOFriends').live('mouseenter click', function(e) {
	$('.hostVOFriends').css('color','#add136');
	if (e.type == "click") {
		$('#hostAF').removeClass('baOut fbFOut');
		if ($('#hostAF').hasClass('isOut') == false) {
			slideHostOut(1);
			$('#hostAF').addClass('isOut voFOut');
		}
		else { 
			if ($('#hostAF').hasClass('voFOut') == false) {
				$('#hostAF').addClass('voFOut');
				slideHostCover(1, 320, 0);
			}
			else if($('#hostAF').hasClass('voFOut') == true) {
				slideHostIn();
				$('#hostAF').removeClass('isOut voFOut');
			}
		}
		$('#hostAF h2 span:first-child').html('VenueOne Friends');
	}
});

//Invite friends from VenueOne li's mouse out
$('.hostVOFriends').live('mouseleave', function() {
	$('.hostVOFriends').css('color','#fff');
});

//Invite friends from Facebook li's click and mouse hover
$('.hostFBFriends').live('mouseenter click', function(e) {
	$('.hostFBFriends').css('color','#add136');
	if (e.type == "click") {
		$('#hostAF').removeClass('baOut voFOut');
		if ($('#hostAF').hasClass('isOut') == false) {
			slideHostOut(1);
			$('#hostAF').addClass('isOut fbFOut');
		}
		
		else { 
			if ($('#hostAF').hasClass('fbFOut') == false) {
				$('#hostAF').addClass('fbFOut');
				slideHostCover(1, 320, 0);
			}
			else if ($('#hostAF').hasClass('fbFOut') == true) {
				slideHostIn();
				$('#hostAF').removeClass('isOut fbFOut');
			}
		}
		$('#hostAF h2 span:first-child').html('Facebook Friends');
	}
});

//Invite friends from Facebook li's click mouse out
$('.hostFBFriends').live('mouseleave', function() {
	$('.hostFBFriends').css('color','#fff');
});

//Search Gigs i Host a Party 
$('#hostPartyGigSearch').live('keyup', function() {
	$(this).searchList({
		'list' : $('#hostPartyGigs')
	});
});
//###############################################################################################



/**
 * * HOST YOUTUBE PARTY
 */
$('#hostYTPartyBtn').live('click', function() {
	if (chat) {
		window.location.hash='#!/createyoutube';
	}
	else {
		notification('Join or Login to create your own YouTube Party!');
	}
})

function getmoduser() {
	for (var i=0; i < shoutout.guests.length; i ++) {
		if (shoutout.guests[i].user_jid == chat.party.partyroom.get_moderator().bare_jid) {
			return shoutout.guests[i];
		}
	}
}

//Edit party Name
var ytSearchVal = '';

function editYTPartyName() {
	$('#hostYouTubeNameBtn').html('save');
	ytSearchVal = $('#hostYouTubeName').val();
	$('#hostYouTubeName').removeClass('hostYouTubeNameInact').removeAttr('readonly');
	$('#hostYouTubeName').focus();
	
	$('#hostYouTubeNameBtn').die('click');
	$('#hostYouTubeNameBtn').live('click', function() {
		saveYTPartyName();
	});
	
}

//Save Youtube party name
function saveYTPartyName() {
	$('#hostYouTubeName').addClass('hostYouTubeNameInact');
	$('#hostYouTubeNameBtn').html('edit');
	$('#hostYouTubeName').attr('readonly','readonly');
	notification("Saving Party Name - " + $('#hostYouTubeName').val(), true);
	chat.party.partyroom.change_subject($('#hostYouTubeName').val(), chat.connection);
	
	$('#hostYouTubeNameBtn').die('click');
	$('#hostYouTubeNameBtn').live('click', function() {
		editYTPartyName();
	});
}

//Is Moderator
function isYTModerator() {
	$('#hostYouTubeNameBtn').removeClass().addClass('orangeBtn orangeGrad rounded');
	$("#ytRoomPlayerWrapper, #hostYouTubeWraper").addClass("moderator");
	//notification("You are now the host of the party! Guests can suggest videos for you to add to the playlist, and you can approve or deny them", true);
	
	$('#hostYouTubeNameBtn').live('click', function() {
		editYTPartyName();
	});
}

//Not Moderator
function notYTModerator() {
	$('#hostYouTubeNameBtn').removeClass().addClass('greyBtn greyGrad rounded');
	$("#ytRoomPlayerWrapper,#hostYouTubeWraper").removeClass("moderator");
	notification("You are not the moderator anymore. LAME.");
	
	$('#hostYouTubeNameBtn').live('click', function() {
		notification("You can't edit the Party Name, because you are not moderator. LAME SHMAME.", true);
	});
}

$(document).bind("leave_youtube", function () {
	
	if (chat) {
		if (chat.party.partyroom.room_jid_resource) {
			chat.party.partyroom.leave();
			$(document).trigger("non_shoutout_room");
		}
	}
	if (typeof ytPlaylist != "undefined") {
		ytPlaylist.clear_iterator();
		ytPlaylist.clear_playlist();
	} 
	
	if (typeof ytPlayerUI != "undefined") {
		ytPlayerUI.clear_progress(); 
	}
});
//#######################################################################################



/*
 * * PARTY HUB
 */
function show_register_slide() {
	notification('You must be logged in to use this feature');
}

//Banner Ad Pop up
$('#partyHubBannerImg').live('click', function() {
	$('.bannerAd').show();
	$('body').bind('click', function() {
		$('.bannerAd').hide();
		$('body').unbind('click');
	});
});

//Show party info id card
$('.partyInfoA').live('click', function(){
	$('.idCardParties').remove();
	$.ajax({
		url: $(this).attr('href'),
		data: 'event_code=' + $(this).data('event_code'),
		success: function(data){
			$(data).appendTo('body').tabs();
		}
	})
	return false;
})

//Show party info id card
$('.event_name.event_active').live('click', function(){
	$('.idCardParties').remove();
	$.ajax({
		url: $(this).attr('href'),
		data: 'event_code=' + $(this).data('event_code')+'&click=true',
		success: function(data){
			$(data).appendTo('body').tabs();
		}
	})
	return false;
})

//Show country name on Flag hover
$('.partyList .country, .hpFlag').live('mouseenter mouseleave', function(e) {
	var pos = $(this).offset();
	if (e.type == 'mouseenter') {
		$('body').append('<div class="fullTrackName rounded black70" style="top: ' + (pos.top+25) + 'px; left: ' + (pos.left) + 'px">' + $(this).data('countryname') + '</div>');
	}
	else {
		$('.fullTrackName').remove();
	}
});

//Extend Gig in Party Info Card
$('.partyCardPluss').live('click', function(){
	var classname = $(this).parent().data('mclass');
	var artist = '.' + classname + 'A';
	
	$('.partyCardArtist, .partyCardSong, .pcFirstVerticalLine').hide();
	
	if ($(this).hasClass('plussExtended') == false) {
		var rclass = '.' + $(artist).last().data('rclass') + 'R';
		
		$('.pcGigExtended').removeClass('pcGigExtended');
		$('.plussExtended').removeClass('plussExtended');
		$(this).addClass('plussExtended');
		$('.' + classname + '').show().addClass('pcGigExtended');			
		$(rclass).remove();	
		$(artist).last().find('.pcVerticalLine').css('height','18px');
	}
	else {
		$(this).removeClass('plussExtended');
		$('.' + classname + '').hide();
		$('.pcGigExtended').removeClass('pcGigExtended');
	}
	
});
//#########################################################################



/*
 * Party landing page
 */
$('#competition_landing_content  .shareFacebook').live('click', function(){
	fbs_click('http://www.venueone.com/#!/fighting-chance');
});

//Timer for CLICK HERE TO ENTER button
function getOClock() {
	var time = new Date();
	var hour = time.getHours();
	var day = time.getDate();
	
	if (chat) {
		$('#landingEnterParty').hide();
		$('#landingOrLogin').hide();
		if ((hour == 20 && day == 13) || (hour == 20 && day == 14)) {
			window.location.hash = '#!/partyhub';
		}
	}

	else {
		$('#landingEnterParty').live('click', function() {
			$.ajax({  
				url: "index.php?r=registration/registration",
				success: function (data)  { 
					$('#regForm').html(data); 
					$('#regForm').yuriBox({
						title:"Register for free to use<br />VenueOne&acute;s social Features"
						,width:330
						,position: [$('#iContent').offset().left + $('#iContent').width() - 350,80 ]
					});
				}
			});
		});
	}
	
}


//Time Countdown on Landing Page
/*function countdowner() {
	var date; 
	var today = new Date();
	var h = today.getHours();
	var d = today.getDate();
	var m = today.getMonth();
	var y = today.getYear();
	
	if(h > 20) {
		 var date= new Date(y, m, d+1);
	}
	else {
		var date = new Date(y, m, d);
	}
	
	var date = new Date(y, m, d);
	var month = date.getMonth()+1;
	var day = date.getDate();
	var today = month + '/' + day + '/2011 ';

	if (h != 20) {
		$("#landingTime").countdown({
			date: today + "21:00",
			htmlTemplate: "<li class='rounded'> %{d}</li><li class='rounded'> %{h}</li><li class='rounded'> %{m}</li><li class='rounded'> %{s}</li>",
			offset: 1,
			onChange: function( event, timer ){ 
			},
			onComplete: function( event ){
				//$('#landingTime, #countdownLabels').hide();
			},
			onPause: function( event, timer ){
				$(this).html("Pause");
			},
			onResume: function( event ){
				$(this).html("Resumed");
			},
			leadingZero: true
		});
	}
	else {
		$('#landingTime, #countdownLabels').hide();
	}
}*/
//#############################################end party landing page
	


 /*
 * *STAGE
 */
//Show Who is playing for few seconds when stage is loaded
function showStageTitleOnLoad() {
	$('#stageTitle').animate({opacity: 1}, 500, function() {
		$(this).delay(15000).animate({opacity: 0}, 500);
	});
}

//Show track info on playe hiver
$('#screenWrapper').live('mouseenter mouseleave', function(e){
	if (e.type == 'mouseenter') {
		$('#stageTitle').stop().animate({opacity: 1}, 500);
	}
	else {
		$('#stageTitle').stop().animate({opacity: 0}, 500);
	}
});

//########## Share Video ##########
//Select Video Link
$('#sVideoLink input').live('click', function() {
	$(this).select();
});
//#################################


//########## Comments ##########
//Write Comments

//TODO also work with ENTER key

function shoutout_enter (DOMelement, evt) {
	var keyCode = evt.keyCode ? evt.keyCode : evt.charCode ? evt.charCode : evt.which;
	
	if (keyCode == 13) {	
		var message_text = $(DOMelement).val();
		try_message(message_text)

		// cancel key:
		if (evt.preventDefault) {
			evt.preventDefault();
		}
		return false;
	}
	return true;
}

$('#sCommentsInput').keypress(function(ev) {
	if (ev.which == 13) {
		var message_text = $('#sCommentsInput').val();
		try_message(message_text);
	}
});

function try_message(message_text) {
	if(chat.my_user_jid) {
		shoutout.send_message(message_text);
		$('#sCommentsInput').val('');
	} else {
		notification("You must sign in to use shoutout!");
	}
}


$('#sCommentBtn').live('click', function(e) {
	console.log(e);
	var message_text = $('#sCommentsInput').val();
	if(chat.my_user_jid) {
		try_message(message_text);
	} else {
		notification("You must sign in to use shoutout!");
	}
	
	$('#sCommentsInput').val('');
});

//Delete Own Comment 
$('.sCommentDelete').live('click', function() {
	$(this).parent().parent().remove();
});

/*
 * *ARCHIVE 
 */
//########## Gig Infromation and Playlist ###########
//Switching between Tracklist and Infromation Tabs
$('#archiveTracklistBtn, .archPlayToBtn, .videoThumb .imageWrap').live('click', function() {
	$('#archiveTracklistBtn').addClass('black40').css('color','#add136');
	$('#archiveTracklistBtn').next().removeClass('black40').css('color','#fff');
	$('#gigInformationTab').hide();
	$('#gigTraclistTab').show();
	$('#iContentWrap').animate({ scrollTop: 0 }, 1000);
});

$('#archiveInfromationBtn').live('click', function() {
	$(this).addClass('black40').css('color','#add136');
	$(this).prev().removeClass('black40').css('color','#ffba00');
	$('#gigInformationTab').show();
	$('#gigTraclistTab').hide();
});

//Click on song in Tracklist
$('.gigTraclistLine').live('click', function() {
	console.log($(this).hasClass('add60'));
	if (!($(this).hasClass('add60'))){
		$('.gigTraclistLine').removeClass('add60').addClass('gigTraclistLineHover').css('color','#fff !important').find('div').css('background-position','-212px -140px');
		$(this).addClass('add60').removeClass('gigTraclistLineHover').css('color','#000 !important');
	}
});

//Show full track name on Hover over
$('.gigTraclistLine').live('mouseenter mouseleave', function(e){
	var pos = $(this).offset();
	if($(this).data('fulltrackname') != 'none' && e.type == 'mouseenter') {
		$('body').append('<div class="fullTrackName rounded black90" style="top: ' + (pos.top+25) + 'px; left: ' + (pos.left+32) + 'px">' + $(this).data('fulltrackname') + '</div>');
	}
	else {
		$('.fullTrackName').remove();
	}
});

//Archive Category Tabs
$('#archiveTabsWrapper li').live('click', function() {
	if($('#archiveTabsWrapper').hasClass('tabsChecker') == false) {
		$('#archiveTabsWrapper li').removeClass('grey40 archActiveTab').addClass('black80');
		$(this).removeClass('black80').addClass('grey40 archActiveTab');
		$('.archTabs').hide();
		
		if ($(this).index() == 0) { $('#archiveArtistTab').show(); }
		if ($(this).index() == 1) { $('#archiveGigsTab').show(); }
		if ($(this).index() == 2) { $('#archiveSResultsTab').show(); }
	}
	else {
		$('#archiveTabsWrapper').removeClass('tabsChecker');
	}
	
});


//close Search tab
$('#searchResultsTab div').live('click', function() {
	$('#archiveTabsWrapper').addClass('tabsChecker');
	$(this).parent().hide();
	//$('.display_search').html('');
	$('#archiveArtistTab').show();
	$('#archiveTabsWrapper li').removeClass('grey40 archActiveTab').addClass('black80');
	$('#archiveTabsWrapper li:eq(0)').removeClass('black80').addClass('grey40 archActiveTab');
});

//open search results on Artist Name or Track Name click
$('#archiveGigsUL .artist, #archiveGigsUL .track').live('click', function() {
	$('.display_search').html('');
	$('#searchResultsTab').show();
	$('#archiveTabsWrapper li').removeClass('grey40 archActiveTab').addClass('black80');
	$('#archiveTabsWrapper li:eq(2)').removeClass('black80').addClass('grey40 archActiveTab');
	$('.archTabs').hide();
	$('#archiveSResultsTab').show();
	$('.hideNoResult').hide();
});


//Video Thumbnails
$('.videoThumb').live('mouseenter mouseleave', function(e) {
	var footer = $('#footer').height();
	var win = $(window).height();
	var botline = win - footer;
	var pos = $(this).find('.thumbBottomRight').offset();
	var sTop  = $('#iContentWrap').scrollTop();
	var multi = Math.ceil(($(this).parent().index() + 1) / 6);
	
	if (e.type == 'mouseenter') {
		if ($(pos).top > botline-4) {
			$(this).css('height','132px');
			$('#iContentWrap').animate({ scrollTop: 112 * (multi-2) }, 200); 
		}
		else {
			$(this).stop().animate({ height: 132 }, 200);
		}
		$(this).css('z-index','3');	
	}
	else {
		$(this).css('z-index','1');
		$(this).stop().animate({ height: 90 });
	}	
});

//Info Pop Up
$('#archiveInfoPreview').live('mouseover mouseout', function(e) {
	if (e.type == 'mouseover') {
		$(this).find('li').css('color','#add136').css('background-position','-187px -129px');
	}
	else {
		$(this).find('li').css('color','#ffba00').css('background-position','-187px -113px');
	}
});
$('#archiveInfoBigScreen').live('mouseover mouseout', function(e) {
	if (e.type == 'mouseover') {
		$(this).find('li').css('color','#add136').css('background-position','-205px -129px');
	}
	else {
		$(this).find('li').css('color','#ffba00').css('background-position','-205px -115px');
	}
});

//Clicking on info button
$('.archInfoBtn').live('click', function(e) {
	var $this = $(this).parent().parent().parent(); 
	var pos = $this.offset();
	var height = $('#idCardArchive').height();
	var width = $('#idCardArchive').width();
	if (e.pageX <= Math.round($(window).width()/2)) {
		$('#idCardArchive').css('left', (pos.left+154) + 'px');
	}
	else {
		$('#idCardArchive').css('left', (pos.left-width-4) + 'px');
	}
	
	if(e.pageY <= Math.round($(window).height()/2)) {
		$('#idCardArchive').css('top', pos.top + 'px');
	}
	else  {
		$('#idCardArchive').css('top', ((pos.top+133)-height) + 'px');
	}
	$('#idCardArchive').show();
});


$(".idCard").live("click",function(e){
	//overwrite the document click that hides the id card
	e.stopPropagation();
	return false;
    });

$(".idCard .closeButton").live("click",function(){
	$(this).parents(".idCard").fadeOut(200);
});



$("body").live("click",function() {
	$(".idCard").fadeOut(200);
});

var goBig = false;

//Transform Archive to big Screen
$('.archBigScreenBtn, .gigTRacklistPlay').live('click', function(){
	goBig = true;
	checkArchiveSize();
});

function checkArchiveSize(){
	if (goBig){
		makeArchiveBig();
	}else{
		makeArchiveSmall();
	}
}

function makeArchiveBig (){
	
	
	var ad = $('#archiveAdWrapper').html();
	
	//window.location.hash = window.location.hash + '/large';
	
	//setTimeout("window.location.hash = window.location.hash + '/large'",1000);
	
	$('#archiveWrapper').addClass('bigView');
	
	$('#playerWrapper').addClass('bigScreenMode');
	//$('.transformation').hide();
	//$('#archiveWrapper').css('border','none');
	//$('#archivePlayerArea').removeClass('grey40');
	$('#archiveAdWrapper').remove();
	
	var dHtml = '<div id="archiveAdWrapper" class="mpu">' + ad + '</div>';
	$('#transformedWrap').prepend(dHtml);
	
	//$('#gigInfowrapper').css({position: 'absolute', top: '368px', right: '34px'});
	//$('#archiveAdWrapper').css('margin','23px 0 0 7px').css('float', 'none');
	//$('#archiveWrapper #playerWrapper').css('margin', '0 0 0 20px').css('width','610px').css('height','390px');
	//$('#archiveWrapper #playerWrapper object').css('width','610px').css('height','390px');
	//$('#gigInfowrapper').css('margin','4px 0 0 8px');
	//$('#archiveWrapper #sCommentsWrapper').show();
	$('.gigTRacklistPlay').removeClass('bigScreenIcon');
	
	if(typeof modVP !== 'undefined') {
		if(modVP.hasOwnProperty('_experience'))
		{
			$('#myExperience')
			.css('width', '610px')
			.css('height', '390px');
		}
	}
}


//Transform Big Screen back to Archive
$('#backToArchive, #archiveBtnHeader').live('click', function(){
	goBig = false;
	checkArchiveSize();
});

function makeArchiveSmall(){
	var ad = $('#archiveAdWrapper').html();
	
	$('#archiveWrapper').removeClass('bigView');
	$('#playerWrapper').removeClass('bigScreenMode');
	//$('.transformation').show();
	//$('#archiveWrapper').css('border-left','1px solid #000').css('border-right','1px solid #000');
	//$('#archivePlayerArea').addClass('grey40');
	$('#archiveAdWrapper').remove();
	//$('#backToArchive').remove();
	//$('#transformedWrap').remove();
	
	$('#archivePlayerArea').append('<div id="archiveAdWrapper" class="mpu">' + ad + '</div>');
	
	//$('#gigInfowrapper').css({position: 'inherit',  top: 'inherit', right: 'inherit'});
	//$('#archiveAdWrapper').css('margin','18px 0 0 14px').css('float', 'left');
	//$('#archiveWrapper #playerWrapper').css('margin', '6px 0 0 10px').css('width','350px').css('height','262px');
	//$('#archiveWrapper #playerWrapper object').css('width','350px').css('height','250px');
	//$('#gigInfowrapper').css('margin','-6px 0 0 14px');
	//$('#archiveWrapper #sCommentsWrapper').hide();
	//$('#archiveWrapper .gigTRacklistPlay').show();
	$('.gigTRacklistPlay').addClass('bigScreenIcon');
	
	if(typeof modVP !== 'undefined') {
		if(modVP.hasOwnProperty('_experience'))
		{
			$('#myExperience')
			.css('width', '350px')
			.css('height', '250px');
		}
	}
};
//###################################################



/**
 * * MY STUFF
 */
function imageUploadOpera() {
	$('#updates_tab_2 .avatarBtns').show(); 
	$('#chooseFileBtn').hide();
	$('#updatesPanel #fileName').hide();
	$('#imageFile').css({opacity: 1, width: 170});
}

//Chose file Fkae Button
$('#chooseFileBtn').live('click', function() {
	$('#imageFile').click();
	$('#imageFile').one('change', function() {
		var splitName = $(this).val().split('\\');
		var ext = $(this).val().split('.');
		ext = ext[ext.length-1];
		if (ext == 'jpg' || ext == 'png' || ext == 'gif' || ext == 'jpeg') {
			$('#avatarBtnsUL li:first-child').show();
			$('#updatesPanel .avatarParam').html(splitName[splitName.length-1]);
			$('#updatesPanel .avatarParam:eq(0)').html('&nbsp;');
			$('#chooseFileBtn').removeClass().addClass('greyBtn greyGrad rounded avatarBtns');
		}
		else {
			notification('Wrong file');
		}
	});
});

//Change user password
$('#profileChangePassBtn').live('click', function() {
	$('#forgotPassPopup').yuriBox({
		title: "Change Password",
		buttons: { 
			"Cancel": function() { $(this).dialog("close");},
			"Confirm": function() {				
				
				var oldPass = $('#changepass-form #OldPassword').val();
				var newPass = $('#changepass-form #NewPassword').val();
				var conNewPass = $('#changepass-form #ConfirmNewPassword').val();
				
				if ((oldPass == '') ||  (newPass == '' || newPass.length < 6) || (conNewPass == '' || conNewPass.length < 6)) {
					notification('Password length minimum 6 chars')
					notification('Please fill out all fields');
				}
				else if (newPass != conNewPass) {
					notification('Password are not match');
				}
				else {					

					$.ajax({
						url: 'index.php?r=mystuff/changepassword',
						type: 'POST',
						data: 'old_password=' + oldPass + '&new_password=' + newPass,
						dataType: "json",
						
						/*
						success: function(data){
							//console(data);
							notification(data);
						},
				        error: function(error){
				        	notification('Your password was changed');				        	
				        }
				        */
						
						success: function(data){													
				        
					        if (data['status'] == 'OK') { 
					        	
					     		notification(data['message']);				        			     		
					     		$(this).dialog("close");
					     		
							}else{
								
								notification(data['message']);
								
								//if (data['error_pass']['password'] != undefined) { 
						     	//	notification(data['error_pass']['password'][0]); 
								//} 					    	
						    	
							}
				        },
				        error: function(error){
				        	notification('Request was not send.');	        	
				        }
				        
					});
				}
				
				
			}
		}
	});
});


$('.logout').live('click', function() {
	if (window.location.hash == '#!partyroom') {
		window.location.hash = '#!';
	}
});

/*
//Save my profile
$(".avatarUplaodForm").live('submit',function(e){
	e.preventDefault();
	href = $(".avatarUplaodForm").attr('action');
	
	post_data = "YumUser[avatar]="+$('#imageFile').val();
	
	$.ajax({
        url:href,
        type:"post",
        data: post_data,
        dataType: "json",
        success: function(data){													
        
	        if (data['status'] == 'OK') { 
	        	
	     		notification(data['message']);				        			     		
	     		$(this).dialog("close");
	     		
			}else{
				
				notification(data['message']);
				
				//if (data['error_pass']['password'] != undefined) { 
		     	//	notification(data['error_pass']['password'][0]); 
				//} 					    	
		    	
			}
        },
        error: function(error){
        	notification('Request was not send.');	        	
        }
	});
	
	
});
*/

//Save my profile
$(".profileForm form").live('submit',function(e){
	e.preventDefault();
	href = $(".profileForm form").attr('action');
	
	/*
	//Data Inputs for submission
	var date;
	var dateYear = $('#pfYearInput').val();
	var dateMonth = $('#pfMonthInput').val();
	var dateDay = $('#pfDayInput').val();
	
	if (dateYear == 'year') { dateYear = '1992'; }
	if (dateMonth == 'month') { dateMonth = '01'; }
	if (dateDay == 'day') { dateDay = '01'; }
	
	date = dateYear + '-' + dateMonth + '-' + dateDay;
	*/
	
	post_data = "Profile[first_name]="+$('#UpdateProfile_name').val() 
    + "&Profile[nick_name]="+$('#UpdateProfile_nickname').val() 
    + "&Profile[nationality]="+$('#countryCodeTrtans').val() 
    + "&Profile[dob_year]="+$('#pfYearInput').val() 
	+ "&Profile[dob_month]="+$('#pfMonthInput').val()
	+ "&Profile[dob_day]="+$('#pfDayInput').val(); 
    
	if ($('#UpdateProfile_name').val() != '' && $('#UpdateProfile_nickname').val() != '' && $('#countryCodeTrtans').val() != '') 
	{
		
		$.ajax({
	        url:href,
	        type:"post",
	        data: post_data,
	        dataType: "json",
	        success: function(data){													
	        
		        if (data['status'] == 'OK') { 
		        	
		     		notification(data['message']);
		     		$('#updatesPanelPname').text($('#UpdateProfile_name').val()); 
		     		$(this).dialog("close");
		     		
				}else{
					
					notification(data['message']);
					
					//if (data['error_pass']['password'] != undefined) { 
			     	//	notification(data['error_pass']['password'][0]); 
					//} 					    	
			    	
				}
	        },
	        error: function(error){
	        	notification('Request was not send.');	        	
	        }
		});
	}
	else {
		notification('Please fill in all fields');
	}
});

//########## My Friends ##########
$('#my_find_friends button').live('click', function() {
	$('#my_find_friends button').removeClass('activeFriendsLink');
	$(this).addClass('activeFriendsLink');
	if ($(this).index() == 1) {
		$('#friendsTabSearchSpan').html('Search my VenueOne friends');
		$('#friendsSocialNetworks').hide();
		$('#mystuff_friends_results').css('top','128px');
		$('#mystuff_friends_results #friendsList').show();
		$('#snFriendsHolder').hide();
		$('#mystuff_friends_results #friendsList').show();
		$('#friendsSocialNetworks li:eq(0)').addClass('activeSN').next().removeClass('activeSN');
		$('#msFindFriendsOn').html('My Friends:');
		$('#socialNetworksBotBorder').hide();
	}
	else {
		$('#friendsSocialNetworks').show();
		$('#mystuff_friends_results').css('top','188px');
		$('#friendsTabSearchSpan').html('Search VenueOne for friends');
		$('#msFindFriendsOn').html('Find Friends on:');
		$('#socialNetworksBotBorder').show();
	}
});

$('#friendsSocialNetworks li').live('click', function() {
	$('#friendsSocialNetworks li').removeClass('activeSN');
	$(this).addClass('activeSN');
	
	if ($(this).index() == 0) {
		$('#friendsTabSearchSpan').html('Search VenueOne for friends');
		$('#mystuff_friends_results #friendsList').show();
		$('#snFriendsHolder').hide();
	}
	
	else {
		$('#friendsTabSearchSpan').html('Search my Facebook friends');
		if ($(this).hasClass('fbFriendsLoaded') == false) {
			$('#mystuff_friends_results #friendsList').hide().html('');
			$('#snFriendsHolder').show();
		}
		else {
			$.ajax({
				type: 'POST',
				url: 'index.php/?r=global/fbgetfriends',
				success: function(data) {
					$('#mystuff_friends_results #friendsList').html(data);
					console.log('Load Facebook Friends');
				}
			});
		} 
	}
});

$('#mystuff_friends_results #getFBFriendsBtn').live('click', function() {
	$.ajax({
		type: 'POST',
		url: 'index.php/?r=global/fbgetfriends',
		success: function(data) {
			$('#snFriendsHolder').hide();
			$('#mystuff_friends_results #friendsList').show().html(data);
			$('#friendsSocialNetworks li:eq(1)').addClass('fbFriendsLoaded').removeAttr('onCLick');
		}
	});
});

$('#hostAF #getFBFriendsBtn').live('click', function() {
	$.ajax({
		type: 'POST',
		url: 'index.php/?r=party/fbgetfriendsforparty',
		success: function(data) {
			$('#hostAF .marginWrapper').append(data);
			$('#hostAF #fb-root, #hostAF #user-info').hide();
		}
	});
});
//#################################




/*
 * * Common Actions
 */
//########## Common Actions - CAF ##########
//Closse Popup window if it has "closeByCancelBtn" class
$('.cancelBtn').live('click', function() {
	$('.closeByCancelBtn').html('').hide();
	fadeInScreen();
});
//##########################################


function readyUpdates(){
	$('.updatesTabs').tabs({
		ajaxOptions : {
			success: function(data){
				//console.log($('#updatesPanel .scrollMe'));
				setScrolls();
			}
		},
		select: function(event, ui) {
			switch (ui.index) {
				case 0 : 	$('#updatesPanel .loadingBar').hide();
				break;
				case 1 :	$('#updatesPanel .loadingBar').show();
				break;
				case 2 : 	$('#updatesPanel .loadingBar').show(); 
							$('#snFriendsHolder').hide(); 
							$('#friendsSocialNetworks li').removeClass('activeSN'); 
							$('#friendsSocialNetworks li:eq(0)').addClass('activeSN');
				break;
			}
		}
	});
}


function setScrolls(){
	$('.scrollMe').each(function(){
		if( !($(this).hasClass('jspScrollable')) ){
			$(this).jScrollPane({
				showArrows: true,
				verticalGutter: -8,
				verticalArrowPositions: 'split',
				horizontalArrowPositions: 'after',
				autoReinitialise: true
				//contentWidth:200
			});
		}
	});
	$('.friendsWrap').jScrollPane({
		showArrows: true,
		autoReinitialise: true
	});
}

//Scroll Pane
function scrollPane() {
	$('.scrollPane').jScrollPane({
		showArrows: true,
		verticalGutter: -8,
		verticalArrowPositions: 'split',
		horizontalArrowPositions: 'after',
		autoReinitialise: true
		//contentWidth:200
	});
}

/*
 * * Footer Pages
 */
//########## On Footer Pages Function ##########
function footerPageReady() {
	$(document).trigger('non_shoutout_room');
	if ($('#footerPagesC .firstLi').hasClass('subsLi') == false) {
		$('#footerPagesC .firstLi').css('color','#817e7e');
	}
	$('#footerPagesC .firstInfo').fadeIn(700);
}

$('#fpMenuEffects li').live('click', function() {
	var buttonId = $(this).attr('id');
	buttonId = buttonId.substring(0, buttonId.length-2);
			
	if ($(this).hasClass('subsLi') == false) { 
		$('#fpMenuEffects li').css('color','#fff').css('text-decoration','none');
		$(this).css('color','#817e7e');
 		if ($('.unvisible').is(':visible')){
 			$('.unvisible:visible').fadeOut(700, function() { 
				$('#' + buttonId + 'Info ').fadeIn(700) 
			});
 		}
	}
	else {
		var rPos = $('#' + buttonId + 'Info ').position();
	  	$('#iContentWrap').animate({scrollTop : rPos.top}, 700);
	}
});

//Go back Button
$('.btt').live('click', function() {
	$('#iContentWrap').animate({scrollTop : 0}, 600);
});	
//##############################################



$('#forgotPassBtn, #footerForgotPassBtn').live('click', function() {
	$('#forgotPassPopup').yuriBox({
		title: "Forgot Password",
		buttons: { 
			"Cancel": function() { $(this).dialog("close");console.log($(this)); },
			"Send": function() {				
				
				
				if ($('input[name$="ForgotPassword[email]"]').val() != '' ) {					
					
					$.ajax({
						url: 'index.php?r=global/forgotpassform',
						type: 'POST',
						data: 'ForgotPassword[email]='+$(this).find("[name='ForgotPassword[email]']").val(),
						dataType: "json",
						success: function(data){													
				        
					        if (data['status'] == 'OK') { 
					        	
					     		notification(data['message']);				        			     		
					     		$('#forgotPassPopup').dialog("close");
					     		
							}else{
								
								notification(data['message']);
								
								//if (data['error_pass']['password'] != undefined) { 
						     	//	notification(data['error_pass']['password'][0]); 
								//} 					    	
						    	
							}
				        },
				        error: function(error){
				        	notification('Request was not send.');	        	
				        }
					});	
					
				  }else{
					  
					  notification('Please fill all fields.');	 
				  }
				
				}
			}
	});
});


/**
 * * CMS
 */
$('.editFeatured').live('click', function() {
	$(this).hide().next().show().next().show();
	$(this).prev().removeClass('black30').addClass('activeScreen');
});

$('.activeFileInput').live('change', function() {
	var val = $(this).val().substr(12);
	$(this).parent().prev().children().attr('value', val).blur();
	$('.activeFileInput').removeClass('activeFileInput');
});

$('.cmsFileBtn').live('click', function(){
	$(this).parent().next().children().addClass('activeFileInput').click();
});

$('.cmsCancelUpload').live('click', function() {
	$(this).parent().hide().prev().hide().prev().show();
	$('.activeScreen').addClass('black30').removeClass('activeScreen');
});

//#################################################



/*
 * *READY
 */
$(document).ready(function(){
	$('#iContent').css('margin-left', ($(window).width()/2 - $('#iContent').width()/2) + 'px');		//Get Width of Browser View port and set margin-left to .container(center content in the middle)
	
	$(window).trigger('hashchange');
	
	/*hash = parseHash(window.location.hash);
    if (hash.length > 0) {
    	load_page(pages[hash], hash);
    }
    
    if (hash != ""){
    	$("#iContent").children("div").css("display","none");
    }*/
    
    $("#updatesPanel .updatesTabs, .idCard").tabs();
    $(".chatPanel").tabs({
    	// Hacked to shit set time out 3 times and it should work crap.. fixme fix me
		   show: function(event, ui) { setTimeout(chat_scroll_bottom,200);setTimeout(chat_scroll_bottom,500);setTimeout(chat_scroll_bottom,1000); }
	});
    //$("#updatesPanelWrap .updatesTabs, .partyTabs, .idCard, .chatPanel").tabs({ fx: { opacity: 'toggle' } });
    $(".idCard").live('mouseenter',function(){
    	$(this).draggable({ containment: "#iContentWrap", scroll: false });
    });


    ready_and_resize();
    
    
    $('.scrollMe').jScrollPane({
	    showArrows: true,
	    verticalGutter: -8,
	    verticalArrowPositions: 'split',
	    horizontalArrowPositions: 'after',
	    autoReinitialise: true
	});
    
    set_chat_drops();  
    

    $(".dPanel").mouseenter(function(){
        $(this).stop(true,true).animate({opacity:1},200).delay(5000).animate({zIndex:10},1);
    }).mouseleave(function(){
    	if ( !( $(this).attr("id")=="chatPanelWrap" && $("#chatPanelWrap").find('input').is( ":focus" ) ) ){
    		$(this).stop(true,true).delay(3000).animate({opacity:0.3,zIndex:""},1000);
    	}
    })
    
    //console.log($("#iContent .pageWrap"));
    
    //hide username and password writing on login form
    setTimeout('clearLoginTitles()',200);
    
});

//END READY

/*
 * * COOKIES
 */
function setCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function deleteCookie(name) {
    setCookie(name,"",-1);
}
//##############################################################################

function clearLoginTitles(){
	if( $('#YumUserLogin_username').val() != ""){
		$('#YumUserLogin_username').siblings('.tfSpan').css("display","none");
	}
	if( $('#YumUserLogin_password').val() != ""){
		$('#YumUserLogin_password').siblings('.tfSpan').css("display","none");
	}
}



pages = new Array();
title = new Array();

pages[""]="site/ajax";
title[""]="VenueOne - Home";

pages["createyoutube"]="party/CreateYoutubeParty";
title["createyoutube"]="Your new youtube party";

pages["partyhub"]="party/hub";
title["partyhub"]="VenueOne - Party Hub";

//pages["partyroom"]="lkadsjfaldsfjsdfafdasdf";
title["partyroom"]="VenueOne - Party with your friends";

title["register"] = "VenueOne - Register";
pages["register"] = "registration/registration&date=true";
title["dateregister"] = "VenueOne - Register For Your Date";
pages["dateregister"] = "registration/registration&date=true";

pages["stage"]="stage/ajax";
title["stage"]="VenueOne - Stage";

pages["archive"]="archive/ajax";
title["archive"]="VenueOne - Archive";

pages["about"]="FooterPages/about";
title["about"]="VenueOne - About";
pages["partners"]="FooterPages/partners";
title["partners"]="VenueOne - Partners";
pages["subscribe"]="FooterPages/subscribe";
title["subscribe"]="VenueOne - Subscribe";
pages["contact"]="footerPages/contact";
title["contact"]="VenueOne - Contact";
pages["help"]="footerPages/help";
title["help"]="VenueOne - Help";
pages["terms"]="footerPages/terms";
title["terms"]="VenueOne - Terms";
pages["privacy"]="footerPages/privacy";
title["privacy"]="VenueOne - Privacy";
pages["fighting-chance"]="party/competitionLanding";
title["morzine"]="VenueOne - Fighting Chance";
pages["svg"]="party/svg";

title["cms"]="VenueOn - Content Managment System";
pages["cms"]="cms/ajax"
	
//To be removed
title["fbActiveInvite"]="Facebook Invite Activation";
pages["fbActiveInvite"]="global/fbActiveInvite";
title["dateroom"]="Lets do sex";
pages["dateroom"]="party/dateroom";
pages["stylewiki"]="global/stylewiki";



function parseHash(hash){
	hash = hash.replace("#!/","");
	hash = hash.replace("#!","");
	hash = hash.replace("#","");
    hash = hash.replace("!/","");
    hash = hash.replace("!","");
    return hash;
}

$(window).bind("hashchange", function(){
	
    hash = parseHash(window.location.hash);
    
    var hashCheck = hash.split('&')
    
    if (hashCheck[0] == 'fbActiveInvite') {
    	var fbid = hashCheck[1].split('=');
    	var codpinf = hashCheck[2].split('=');
    	hash = hashCheck[0];
    	setCookie('fbid', fbid[1], 1);
    	setCookie('codpinf', codpinf[1], 1);
    }
	
    load_page(pages[hash],hash);
})

function refresh_iContent(){
	$(window).trigger('hashchange');
}

$('a').live('click', function(){
	if (window.location.hash == $(this).attr('href') ){
		refresh_iContent();
	}
});

createYoutubeFlag = false;

function load_page(page_index,hash){
	
	setLoading();
	
	$(document).trigger("leave_youtube")
	
	if(hash == "partyroom"){
		if($("#homePageC").length > 0){
			window.location.hash = "#!partyhub";
		} else {
			stopLoading();
			return false;
		}
	}
	
	if(hash == "createyoutube"){
		createYoutubeFlag = true;
	}
	
	if ( window.location.hash.match(/[0-9]\/[A-Z]/i) ){
    	if ($("#archiveWrapper").length>0){
    		checkArchiveSize();
    		stopLoading();
    		return false;
    	} else {

    		
			hash = parseHash(hash);
	    	hash = hash.split('/');
	    	videoId = hash[0];
	    	
	    	$.ajax({
	    		url: 'index.php/?r=archive/ajax',
	    		type: 'POST',
	    		data : 'video_id='+videoId,
	    		success: function(data){
	    			new_page = $(data);
	    		    $("#iContent").html(new_page);
	    		    new_page.addClass('pageContent');
	    		    ready_and_resize();
	    		    checkArchiveSize();
	    		}
	    	})
	    	stopLoading();
	    	return false;
    	}
    }
	
	
	if (window.location.hash.indexOf("youtubeparty/")>=0){
		
		if (createYoutubeFlag){
			createYoutubeFlag = false;
	    	stopLoading();
			return false;
		}
		
		party_md5 = window.location.hash.split("/");
    	URL = "?r=party/youtuberoom&party_md5="+party_md5[party_md5.length-1];
		$("body").attr("data-showing","youtuberoom");
    } else if (window.location.hash.indexOf("partyroom/")>=0 || window.location.hash.indexOf("dateroom/")>=0){
		party_md5 = window.location.hash.split("/");
    	URL = "?r=party/partyhandler&party_md5="+party_md5[party_md5.length-1];
    	if (window.location.hash.indexOf("dateroom/")>=0){
    		$("body").attr("data-showing","dateroom");
    	} else {
    		$("body").attr("data-showing","partyroom");
    	}
    } else if (window.location.hash.indexOf("blog")>=0){
    	URL = window.location.hash.replace("#!/","");
    	$("body").attr("data-showing","blogs");
    }  else {
		
		$("body").attr("data-showing",hash);

	    URL = "index.php?r="+page_index
	    if (pages[page_index]==undefined){
	    	url = "parseHash.php?page="+page_index
	    }
	    
	    document.title=title[hash];
	    mainPageTitle = title[hash];
    }
    
    $.ajax({
	url:URL,
	error: function(){
		stopLoading();
	},
	success: function(data){
	    new_page = $(data);
	    
	    stopLoading();
	    
	    //console.log(new_page);
	    //$("#iContent .jspContainer .jspPane").html(new_page);
	    $("#iContent").html(new_page);
	    
	    $("#iContent a").each(function(){
	    	href = $(this).attr('href')+"";
	    	href = href.replace(/(.*?)blog/gi,"#!/blog")
	    	$(this).attr('href',href);
	    })
	    
	    new_page.first().addClass('pageContent')
	    
	    //console.log(new_page.width()+15);
	    
	    //$("#iContent, #iContent .jspContainer, #iContent .jspPane").width( new_page.width()+15 );
	    
//	    $("#iContent").jScrollPane(
//	    		{
//	    			showArrows: true,
//	    			verticalGutter: -8,
//	    			verticalArrowPositions: 'split',
//	    			horizontalArrowPositions: 'after',
//	    			autoReinitialise: true,
//	    		}
//	    );
	    
	   /* $("#iContent img").load(function(){
		console.log( "pageWrap image loaded "+$(this).attr("src") );
		
		ready_and_resize();
		
	    });*/
	    
	   $("#iContentWrap").animate({scrollTop:0},400);
		
	    ready_and_resize();
	    
	}
    });
}




$(window).bind("resize",function(ev){
    if (ev.target == window ){
        //console.log(ev.target);
        ready_and_resize();

    	//$('.tooltip').remove();
    	//$('.errortip').remove();
    }
});

function ready_and_resize(){
    set_resize_function();
    chat_scroll_bottom();
}



//########## Window Resize ##########

function set_resize_function() {
    // the height of the area inbetween the header and the footer
	
	//$("#iContent").data('jsp').reinitialise();
	//$("#iContent, #iContent .jspContainer, #iContent .jspPane").width( $("#iContent .jspPane").children().width()+15 );
    
    headerHeight = $("#header").outerHeight();
     footerHeight = $("#footer").outerHeight()
     windwoHeight = $(window).height();
     windowWidth = $("html").width();
     middleAreaHeight = windwoHeight-headerHeight-footerHeight;
    $("#iContentWrap").css({
        top: headerHeight,
        bottom: footerHeight
    })
    
    //$("#iContentWrap").css({ bottom: footerHeight })

    $("#friendsOnline, #updatesPanelWrap, #hostYouTubeWraper, #sCommentsWrapper").css({ 
    	top: headerHeight,
    	bottom: footerHeight
    })
    
    $( ".chatPanel.resizable_NE" ).resizable({
        handles: 'n,ne,e',
        maxHeight: middleAreaHeight-10,
        maxWidth: windowWidth/2,
        stop: function(event, ui) { chat_scroll_bottom() }
    });
    
    if ($("#iContentWrap").outerHeight(true) < $("#iContent").outerHeight(true)){
    	$("#updatesPanelWrap, #hostYouTubeWraper, #sCommentsWrapper").css({right:"20px"});
    }else {
    	$("#updatesPanelWrap, #hostYouTubeWraper, #sCommentsWrapper").css({right:"0px"});
    }
    
    resizeFrendsOnline();
    
    $("#iContent").css({width:$($("#iContent").children()[0]).outerWidth(true)+"px !important"});
    
    if ($("#updatesPanelWrap").is(":visible")  || $("#hostYouTubeWraper").length > 0 || $("#sCommentsWrapper").is(":visible")){
    	theLeft = ((windowWidth-$("#iContent").outerWidth()-340)/2 >50) ? (windowWidth-$("#iContent").outerWidth()-340)/2 : 50;
    	$("#iContent").css({marginLeft: theLeft+"px"});
    } else {
    	$("#iContent").css({ marginLeft: ( windowWidth-$("#iContent").width() )/2+'px' });
    }
    
	
    $(".chatPanel.resizable_NE, .shoutOutTabs").css({
        width: (windowWidth-$("#iContent").outerWidth()-120)/2,
        height: ( middleAreaHeight/2 )
    });
    $("#updatesPanelWrap" ).height( middleAreaHeight );

}

function resizeFrendsOnline(){
		friendsOnlineHeight = ($(window).height() - $("#footer").outerHeight() - $("#header").outerHeight() - $("#friendsOnline .title").outerHeight() ) ;
		$("#friendsOnline .friendsWrap").height(friendsOnlineHeight);
}

function chat_scroll_bottom(){
	if ($(".chatPanel .messageBox.jspScrollable").length>0){
		$(".chatPanel .messageBox.jspScrollable").each(function(){
			$(this).data('jsp').scrollToPercentY(100);
		})
	}
}


/*
 * * HEADER ICONS TRIO FUNCTIONS
 */
//Activate YouTube Room Icons ans Show You Tube Search Tab
function activate_yt_room() {
	$('#shoutOutArrow').addClass('soArrowWorking');
	$('#youTubeArrow').addClass('ytArrowActive').removeClass('ytArrowWorking');
	$('#hostYouTubeWraper').show();
	deactivate_shout_out()
	hid_updates_panel();
	$('#youTubeArrow').addClass('isOpened');
	$('#persistNotifications').addClass("offset");
	$('#notifications').addClass("offset");
}

function deactivate_yt_room() {
	$('#youTubeArrow').removeClass('ytArrowActive').addClass('ytArrowWorking');
	$('#hostYouTubeWraper').hide();
	$('#youTubeArrow').removeClass('isOpened');
	activate_shout_out();
}

$('#youTubeArrow').live('click', function() {
	if ($('body').attr('data-showing') == 'youtuberoom' || $('body').attr('data-showing') == 'createyoutube') {
		if ($(this).hasClass('isOpened') == false) {
			activate_yt_room();
		}
		else {
			deactivate_yt_room();
		}
		
	}
});
//--------------------------------------------------------

//Activate Shout Out Icons And show Shout Out Tab
function activate_shout_out() {
	$('#shoutOutArrow').removeClass('soArrowWorking').addClass('soArrowActive');
	$('#sCommentsWrapper').show();
	$('#shoutOutArrow').addClass('isOpened');
	$('#persistNotifications').addClass("offset");
	$('#notifications').addClass("offset");
}
function deactivate_shout_out() {			//TODO we also have a document.bind for tihs
	$('#shoutOutArrow').addClass('soArrowWorking').removeClass('soArrowActive');
	$('#sCommentsWrapper').hide();
	$('#shoutOutArrow').removeClass('isOpened');
	$('#persistNotifications').removeClass("offset");
	$('#notifications').removeClass("offset");
}

$('#shoutOutArrow').live('click', function() {
	if ($('body').attr('data-showing') == 'youtuberoom' || $('body').attr('data-showing') == 'createyoutube' || $('body').attr('data-showing') == 'stage' || $('body').attr('data-showing') == 'partyroom') {
		if ($(this).hasClass('isOpened') == false) {
			deactivate_yt_room();
			hid_updates_panel();
			activate_shout_out();
		}
		else {
			deactivate_shout_out();
		}
		
	}
});
//-----------------------------------------------

//Show Updates Panel
function show_updates_panel() {
	deactivate_yt_room();
	deactivate_shout_out();
	$('#setArrow').addClass('setArrowActive');
    $("#updatesPanelWrap").stop(true,true).fadeIn(200).addClass("manualOpened");
    chat_scroll_bottom();
    $('#setArrow .orangeBox').hide();

    if ($("body").hasClass("sidebarSingle")){
        $("#iContentWrap").css("right","600px");
    }

	$('#persistNotifications').addClass("offset");
	$('#notifications').addClass("offset");
}

//Hide Updates Panel
function hid_updates_panel() {
	$('#setArrow').removeClass('setArrowActive');
    $("#updatesPanelWrap").stop(true,true).removeClass("autoOpened").removeClass("manualOpened").hide();
    if ($("body").hasClass("sidebarSingle")){
        $("#iContentWrap").css("right","0px");
    }

	$('#persistNotifications').removeClass("offset");
	$('#notifications').removeClass("offset");
}

$(".toggleUpdates, #headerFindFriendsBtn").live("click", function(){
	if ( $("#updatesPanelWrap").css("display") == "none"){
		show_updates_panel();
		if($('.jspPane').children('li').length==1){
			console.log("welcomMessage");
		};
    }
	else {
    	hid_updates_panel();
    }

	set_resize_function();

	if ($(this).hasClass('toggleUpdates') == false) {
		 $('.updatesTabBtn li:last-child a').click();
	}
});
//##############################################################################



$(".toggleChat").live("click", function(){
	if (chat) {
	    toggleElement( $("#chatPanelWrap"));
	    if($(".chatPanel .empty").length == 6){
	    	chatAdvice();
	    }
		else{
			$("#dragInAdvice").remove();
		}
	} else {
		notification('You must be logged in to use this feature');
	}
});

function chatAdvice(){
	if(chat.rooms.length <1){
		$("#dragInAdvice").remove();
		$(".chatPanel").append("<div id='dragInAdvice' class='yellow resizable_NE ui-resizable chatBox'><div id='chat_img_div'><img id='chat_img'src='images/chat/chatPlus_1.png'></div><br/><span class='bold inactive_drag'>Drag and drop guests here to chat<div class='textareaWrap'><img class='smallChatIcon'src='images/chat/smallChatIcon.png'><div class='chat_input inactive_chat_input'>chat here</div></div></div>");
	    $("#chatPanelWrap .ui-tabs-nav li.add").css("display","block");
	}
	else{
		$("#dragInAdvice").remove();
	}
}

$(".togglePlaylist").live("click", function(){
    toggleElement( $("#playlistPanelWrap") );
});

function toggleElement( target ){
    if ( target.css("display") == "none"){
        target.stop(true,true).fadeIn(200).addClass("manualOpened");
        chat_scroll_bottom()
    }else{
        target.stop(true,true).removeClass("autoOpened").removeClass("manualOpened").fadeOut(200);
    }
}





$("#chatPanelWrap .closeButton").live("click", function(){
    $("#chatPanelWrap").fadeOut(200);
});

$("#playlistPanelWrap .closeButton").live("click", function(){
    $("#playlistPanelWrap").fadeOut(200);
});


$(".sCommentWrite").live('click',function(){
	console.log($(this));
	$.ajax({
		url: 'index.php?r=mystuff/createmessage&tab=2&userProfile='+($(this).data('user_jid').split("@")[0]),
		success: function(data){
			$(data).appendTo('body').tabs();
		}
	});
});


/*
 * DISABLED CHAT
 */

$(".chatDragger").live('click',function(){
	$.ajax({
		url: 'index.php?r=mystuff/createmessage&tab=1&userProfile='+($(this).data('user_jid').split("@")[0]),
		success: function(data){
			$(data).appendTo('body').tabs();
		}
	});
}).live("mouseenter", function(){
    $(this).draggable({
        containment: "body",
        scroll: false,
        helper: 'clone',
        appendTo: 'body',
        zIndex: 10001,
        cursorAt: { left: 30, top:30 },
        start: function(event, ui) {
                ui.helper.addClass("dragger")
                $("#chatPanelWrap").addClass("seeMe");
                //console.log($("#chatPanelWrap .chatBox.empty").length > 0);
                //if ( $("#chatPanelWrap .chatBox .empty").length > 0 ){
                    $("#chatPanelWrap .ui-tabs-nav li.add").css("display","");
                    //chatAdvice();
                    $('#chat_img').css('margin-top', '-117px')
                //} else {
                    //$("#chatPanelWrap .ui-tabs-nav li.add").css("display","none");
               // }
                
                    //console.log($("#chatPanelWrap .ui-tabs-nav li.add"))
                    
                    //console.log($("#chatPanelWrap .chatBox.empty").length)
        },
        stop: function (event, ui) {
            	$("#chatPanelWrap .ui-tabs-nav li.add").css("display","block");
                $("#chatPanelWrap").removeClass("seeMe");
                $('#chat_img').css('margin-top', '3px')

        //if this area is empty....
        }
});
})
/**
*
*CHAT STUFF
*
**/
flashChat = new Array();

function flash_orange_box(index, stop){
	if (stop){
		clearInterval(flashChat[index]);
		flashChat[index] = undefined;
	} else if (typeof flashChat[index] == "undefined"){
		flashChat[index] = setInterval(function(){ $("#chatbar"+index).siblings(".orangeBox").fadeOut(100).fadeIn(100);},400);
	}
}

var winFocus = true;
var flashTitleMsg;
var flashTitleFirst = true;
var flashTitleTimeout;
window.onblur = function () {winFocus = false; }
window.onfocus = function () {winFocus = true; flashTitle(false); }

function flashTitle (msg){
        if (!msg || winFocus){
        	document.title = mainPageTitle;
                clearInterval(flashTitleTimeout);
                flashTitleFirst = true;
        } else {
                flashTitleMsg = msg;

                if(flashTitleFirst){
                        flashTitleFirst = false;
                        flashTitleTimeout = setInterval('flashTitleToggle()',1000);
                }
        }
}
function flashTitleToggle(){

        if( document.title == mainPageTitle ){
        	document.title = flashTitleMsg;
        } else {
        	document.title = mainPageTitle;
        }
}


function set_chat_drops(){
	
	
	$("#chatPanelWrap ul.users").droppable({
        accept: '.chatDragger',
        drop: function(event, ui) {
        	invite_user_jid = ui.helper.data("user_jid");
            chat_id = $(this).parent().attr("id").charAt($(this).parent().attr("id").length-1);

            invite_room_jid = chat.find_room_jid(chat_id);
            invite_room_key = chat.find_room_key(chat_id); 
            
            chat.invite_to_room(invite_user_jid, invite_room_jid, invite_room_key);
        	
            $("#chatPanelWrap").css("display","block");
        }
    });
	
    $("#chatPanelWrap .chatBox").droppable({
        accept: '.chatDragger',
        drop: function(event, ui) {


            invite_user_jid = ui.helper.data("user_jid");
            chat_id = $(this).attr("id").charAt($(this).attr("id").length-1);
            
            invite_room_jid = chat.find_room_jid(chat_id);
            invite_room_key = chat.find_room_key(chat_id); 
            
            chat.invite_to_room(invite_user_jid, invite_room_jid, invite_room_key);

            
            $("#chatPanelWrap").css("display","block");
        }
    });
    
    
    $("#chatPanelWrap .ui-tabs-nav li").droppable({
        accept: '.chatDragger',
        over: function(event, ui) {
            chat_id = $(this).find("a").attr("href");
            $(".chatPanel").tabs( "select" , chat_id )
        },
        
        drop: function(event, ui) {

            chat_id = $(this).find("a").attr("href").charAt($(this).find("a").attr("href").length-1);
            invite_user_jid = ui.helper.data("user_jid");
            
            invite_room_jid = chat.find_room_jid(chat_id);
            invite_room_key = chat.find_room_key(chat_id);
            
            chat.invite_to_room(invite_user_jid, invite_room_jid, invite_room_key);
            
            $("#chatPanelWrap").css("display","block");
        }
    });

    $("#chatPanelWrap").droppable({
        accept: '.chatDragger',
        drop: function(event, ui) {
    		if($(".chatPanel .empty").length >0){
                chat.create_room(ui.helper.data("user_jid"));
                $("#dragInAdvice").remove();
    		}
        }
    });
    
    $("#chatPanelWrap .toolbarBody li.add").droppable({
        accept: '.chatDragger',
        hoverClass: "highlighted",
        over: function(event, ui) {

            chat_id = $(this).find("a").attr("href");			
            $(".chatPanel").tabs( "select" , chat_id );
        },
        drop: function(event, ui) {

            chat.create_room(ui.helper.data("user_jid"));
            $("#dragInAdvice").remove();
        
        }
    });
}

function create_new_room(){								
    first_available_chat_room = $( $("#chatPanelWrap .chatBox.empty")[0] );
    if (first_available_chat_room.length > 0 ){
        
        
        first_available_chat_room.removeClass("empty");

        $('#chatPanelWrap .ui-tabs-nav li a[href="#' + first_available_chat_room.attr("id") + '"]' ).parent().css("display","block");
        
        $("#chatPanelWrap").css("display","block");
        $(".chatPanel").tabs( "select" , first_available_chat_room.attr("id") )
    } else {
    }
}

function ui_empty_room(room_index) {
	var room = get_room_object_from_id("chat" + room_index)
	var bar = $('#chatbar' + room_index);
	room.find(".users").find('.chatDragger').remove();
	room.find('ul.mixColorList').empty();
	room.addClass('empty');
	bar.parent("li").css("display","none");
	bar.find('img').attr("src", "images/plus30.jpg");
}

function ui_add_user_to_room(user_element, room_id){
    get_room_object_from_id(room_id).find(".users").prepend(user_to_li(user_element) );
}


function user_to_li(jQueryObject){
	var newElement = $("<li></li>");
	$.each(jQueryObject[0].attributes, function(index) {
		$(newElement).attr(jQueryObject[0].attributes[index].name, jQueryObject[0].attributes[index].value);
	});
	newElement.html( jQueryObject.html() )
	jQueryObject.remove();
	return newElement;
}

function get_room_object_from_id(room_id) {
	console.log ("get_room_object");
    return $("#"+room_id);
}


// NOTIFICATIONS NOTE

$('.note .cancelBtn, .note button').live("click",function(){
	$(this).parents(".note").remove();
})

function notification(text_content, options ){
	
	
	var settings = $.extend( {
		'image' : false,
		'persist': false,
		'button1': false,
		'button2': false,
		'title': false,
		'jid' : false,
		'orange_box_el' : false
	}, options);
	
	if(settings.orange_box_el){
		el = $(settings.orange_box_el)
		el.children(".orangeBox").remove();
		if (text_content > 0){
			orangeBox = $('<div class="orangeBox">'+text_content+'</div>').appendTo(el);
			inter = setInterval(function(){orangeBox.fadeOut(200).fadeIn(200);},1000);
			el.click(function(){clearInterval(inter);orangeBox.fadeIn(200)})
		}
		return el;
	}
	
	new_note = $("<div class='note'></div>");
	
	if (settings.persist == true){
		
		dhtml = "<div class='cancelBtn'>X</div>";
		if(settings.title){ dhtml += "<div class='title'>"+settings.title+"</div>" }
		if(settings.image){ dhtml += "<li><img class='pic yellowborder' src='"+settings.image+"' /></li>" }
		dhtml += "<ul><li><div class='notesRight'><div class='notificationText'>" + text_content +"</div></div></li></ul>"
		
		new_note.html(dhtml);

		new_note.prependTo("#persistNotifications").slideDown(400).delay(1000);
		new_note.delay(7000).animate({opacity: 0.5},1000);
		new_note.mouseenter(function(){
	    	$(this).stop(true,true);
			$(this).animate({opacity: 1},100);
	    }).mouseleave(function(){
	    	$(this).delay(4000).animate({opacity: 0.5},1000);
	    })
	    new_note.find('.notesRight').append("<div class='buttonWrap'></div>");
		if(settings.button1){
			var button1_id = Utility.get_random_number();
			var button1_selector = "#" + button1_id;
		    new_note.find('.buttonWrap').append("<button class='btn1' id='"+button1_id+"'>"+settings.button1.text+"</button>");
		    $(button1_selector).bind("click", settings.button1.action);
		    
		}
		if(settings.button2){			
			var button2_id = Utility.get_random_number();
			var button2_selector = "#" + button2_id;
		    new_note.find('.buttonWrap').append("<button class='btn2' id='"+button2_id+"'>"+settings.button2.text+"</button>");
		    $(button2_selector).bind("click", settings.button2.action);
		    
		}

		//button1.text
		/*$('.btn2').click(function(){
	    	thisNote = $(this).parents('.note');
	    	thisNote.html('Your thing with the thing will be thing very thing');
	    	thisNote.delay(3000).fadeOut(400);
	    })*/
	    
	} else {
		new_note.html("<div class='noteExclamation'></div>" + text_content);
		if (settings.jid && $("#friendsOnline li[data-user_jid='"+settings.jid+"']").length>0 ){
			friendOffset = $("#friendsOnline li[data-user_jid='"+settings.jid+"']").offset();
			new_note.addClass("besideFriendsOnline").css({position:"absolute",top:friendOffset.top,left:friendOffset.left+48}).appendTo("body").fadeIn(400);
		}else{
			new_note.prependTo("#notifications").slideDown(400);
		}
		
		new_note.delay(4000).fadeOut(400);
		new_note.mouseenter(function(){
	    	$(this).stop(true,true);
	    }).mouseleave(function(){
	    	$(this).delay(3000).fadeOut(400);
	    })
	}
}




function create_user_html(user_jid, thumbnail, user_name, element, user_id)	{
	element = (!element) ? 'li' : element=element ;
	html = "<"+element+" class='chatDragger ui-draggable' data-jid='";
	html += user_jid
	html += "' data-user_id ='";
	html += user_id;
	html += "'>";
	html += "<img src='" + thumbnail +"'/>";
	html += "<span class='username'>" + user_name + "</span>";
	html +=	 "</"+element+">";
	return html;
}
		
// Facebook Share

function fbs_click(link) {
	if (link) {
		u = link;
	}
	else {
		u = $('.theVideoShare .shareLink').val();
	}
	t=mainPageTitle;
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}

function ts_click() {
	u=$('.theVideoShare .shareLink').val();
	t=mainPageTitle;
	window.open('https://twitter.com/share?original_referer=http%3A%2F%2Fvenueone.com%2F&related=VenueOne&text='+encodeURIComponent(t)+'&via=VenueOne&url='+encodeURIComponent(u),'sharer','toolbar=0,status=0,width=626,height=252')
	//https://twitter.com/intent/tweet?original_referer=http%3A%2F%2Fvenueone.com%2F&related=VenueOne&text=VenueOne+-+Stage&url=http%3A%2F%2Fvenueone.com%2F&via=VenueOne#!/1109924717001/Atomic-Kitten/Whole-Again
	return false;
}

$(document).on("click",".partyShareButton", function(){
	button = $(this);
	url = ( button.parents(".partyShare").length > 0 ) ? button.parents(".partyShare").find("input").val() : button.parents(".sharePartyWrap").find("input").val();
	t = button.data('title')
	
	if(button.hasClass('twitter')){
		window.open(
				'https://twitter.com/share?original_referer=http%3A%2F%2Fvenueone.com%2F&related=VenueOne&text='+encodeURIComponent(t)+'&via=VenueOne&url='+encodeURIComponent(url)
				,'sharer'
				,'toolbar=0,status=0,width=626,height=252')
	} else {
		window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(url)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=645,height=512');
	}
	
})


$(".partyTitle .showShareParty").live("click",function(){
	if($(".partyTitle .partyShare").is(":visible") ){
		$(".partyTitle .partyShare").slideUp(200);
		$(this).text("share party");
		$("#ytRoomPlayerWrapper .showShareParty").css("border", "1px solid white");
	}else{
		$(".partyTitle .partyShare").slideDown(200);
		$(this).text("cancel");
		$("#ytRoomPlayerWrapper .showShareParty").css("border", "1px solid #CD9600");
		
	}
});

$(document).on("click",function(){
	$(".documentHide").css('display','none');
	$(".documentRemove").remove();
});

$(document).on("click",".sharePartyWrap > .shareParty",function(e){
	shareBox = $(this).siblings('.shareWrap');
	console.log(shareBox);
	if ( shareBox.is(':visible') ){
		shareBox.css('display','none');
	}else {
		shareBox.css('display','block');
	}
	e.stopPropigation();
});
$(document).on("click",".sharePartyWrap > .shareWrap",function(e){
	e.stopPropigation();
});

$(document).on("click",".shareExpandButton",function(){
	shares = $(".bothShareWrap");
	if (shares.is(":visible")){
		shares.slideUp()
	} else {
		shares.slideDown();
	}
})

function setShare(id,title,artist){
	
	$('.stageTitle').html(title+' - '+artist);
	
	title = title.replace(/\s/g,'-').replace(/[^a-zA-Z0-9-_]/g, '');
	artist = artist.replace(/\s/g,'-').replace(/[^a-zA-Z0-9-_]/g, '');
	
	urlTitle = artist+'/'+title;
	document.title = "VenueOne - "+artist+" - "+title;
	mainPageTitle = "VenueOne - "+artist+" - "+title;
	//console.log('function: setShare('+id+','+title+','+artist+') urlTitle:'+urlTitle)
//	window.location.hash='#!/'+id+'/'+encodeURI(urlTitle);
	
	//console.log(window.location.hash);
	
	$('.theVideoShare .shareLink').val(Utility.getBaseURL() + '#!/'+id+'/'+encodeURI(urlTitle));
	
	
}

// WORDPRESS BLOG

$("a.disabled").live('click', function(e){
	e.preventDefault();
})

$('.daveBlog form').live('submit', function(e){
	e.preventDefault();
	dataStuff = '';
	$(this).find('input,textarea').each(function(){
		dataStuff+= $(this).attr('name')+"="+$(this).val()+'&';
	});
	
	if($(this).find('#url').val()==""){
		notification('Subject is Required');
		return false;
	}
	
	$.ajax({
		url: $(this).attr('action'),
		type: 'post',
		data: dataStuff,
		success: function(data){
			if ($(data).find('body#error-page').length>0){
				notification($(data).find('p').html())
			}else {
				$('#iContent').html(data);
			}
		},
		error: function(error,s,f){
			//console.log(error)
			//console.log(s)
			//console.log(f)
			var d = $(error['responseText']);
			console.log(d);
			notification($(d[d.length-2]).html())
		}
	})
	
})


$('.inviteToChat').live('click', function () { 
	if ($(this).is(".newChat")) {
		chat.create_room($(this).data("user_jid"));
	} else {
		
		var chat_id = $(this).data("room_index");
		console.log(chat_id);
		var invite_user_jid = $(this).data("user_jid");
		console.log(invite_user_jid);
	    invite_room_jid = chat.find_room_jid(chat_id);
	    
	    invite_room_key = chat.find_room_key(chat_id);
	    
	    chat.invite_to_room(invite_user_jid, invite_room_jid, invite_room_key);
		
	
	}
    
});




//
//	DISABLED STUFF
//




