/**
 * MAIN FUNCTIONS javascript
 *
 * @author 	Francois Arbour
 * @since 	August 19, 2009
 */
 
 
 jQuery.cookie = function(name, value, options) {
		if (typeof value != 'undefined'  ||  (name  &&  typeof name != 'string')) { // name and value given, set cookie
			if (typeof name == 'string') {
				options = options || {};
				if (value === null) {
					value = '';
					options.expires = -1;
				}
				var expires = '';
				if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
					var date;
					if (typeof options.expires == 'number') {
						date = new Date();
						date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
						
					} else {
						date = options.expires;
					}
					expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
				}
				// CAUTION: Needed to parenthesize options.path and options.domain
				// in the following expressions, otherwise they evaluate to undefined
				// in the packed version for some reason...
				var path = options.path ? '; path=' + (options.path) : '';
				var domain = options.domain ? '; domain=' + (options.domain) : '';
				var secure = options.secure ? '; secure' : '';
				document.cookie = name + '=' + encodeURIComponent(value) + expires + path + domain + secure;
			} else { // `name` is really an object of multiple cookies to be set.
			  for (var n in name) { jQuery.cookie(n, name[n], value||options); }
			}
		} else { // get cookie (or all cookies if name is not provided)
			var returnValue = {};
			if (document.cookie) {
				var cookies = document.cookie.split(';');
				for (var i = 0; i < cookies.length; i++) {
					var cookie = jQuery.trim(cookies[i]);
					// Does this cookie string begin with the name we want?
					if (!name) {
						var nameLength = cookie.indexOf('=');
						returnValue[ cookie.substr(0, nameLength)] = decodeURIComponent(cookie.substr(nameLength+1));
					} else if (cookie.substr(0, name.length + 1) == (name + '=')) {
						returnValue = decodeURIComponent(cookie.substr(name.length + 1));
						break;
					}
				}
			}
			return returnValue;
		}
	};


//*****************************************************************************************************************************/
//******************************************************** TOOLS **************************************************************/
//*****************************************************************************************************************************/

// Allows to store metadata into the rel attribute of a dom element
function getAttr(o,attr){
	eval('var arr = '+o.attr("rel"));
	return arr[attr];
}

function rgb2hex(rgb) {
	var rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
	function hex(x) {
		hexDigits = new Array("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");
		return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
	}
	return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}



//*****************************************************************************************************************************/
//**************************************** LOGIN BOX BY FRANCOIS ARBOUR AUG 21 2009 *******************************************/
//*****************************************************************************************************************************/

// this is the page to go to after a successfull login
var goto_page = '';

function openLoginBox(page_name){
	isFocused = true;
	if ($.browser.msie && $.browser.version.substr(0,1)<7) {
		$("select").hide();
	}
	
	$("#login-box").show();
	
	$("#login-box #back").fadeTo( 0, 0).fadeTo( 300, 0.6);
	$("#login-box #inside").fadeTo( 0, 0).fadeTo( 300, 0).fadeTo( 300, 1);
	reposLogin();
	goto_page = page_name;
	$("#new-member").hide();
	$("#returning").show();
	$("#got-login").hide();
	
	if (goto_page == SITE_PATH + 'cart/index/checkout')
	{
		$("#login-box #new").hide();
		$("#login-box #continue").show();
	}
	else if(goto_page == SITE_PATH + 'member') {
		$("#returning").hide();
		$("#got-login").show();
		$("#login-box #new").hide();
		$("#login-box #new-member").show();
	}
	else
	{
		$("#login-box #new").show();
		$("#login-box #continue").hide();
		$('#user').focus();
	}
	
	$("#login-form").submit(function(){
	  submitLogin();
	  return false;
	})

	$("#create-form").submit(function(){
	  submitCreate();
	  return false;
	})
	
	$("#login-box #back").click(function(){
		closeLoginBox();
		return false;
	})
	
	$("#login-box #close-bt").click(function(){
		closeLoginBox();
		return false;
	})
	 
  	$(".create-account-bt").click(function(){
		$("#login-box #new").hide();
		$("#login-box #continue").hide();
		$("#returning").hide();
		$("#new-member").show();
		$("#got-login").show();
	})
	
  	$("#login-account-bt").click(function(){
		$("#login-box #new").show();
		$("#login-box #continue").hide();
		$("#returning").show();
		$("#new-member").hide();
		$("#got-login").hide();
	})
	
	$('#pass').keypress(function(e){
		if(e.keyCode == 9) {
			$('#user').focus();
			return false;
		}
	})
	
	$('#repeat_pass').keypress(function(e){
		if(e.keyCode == 9) {
			$('#user_create').focus();
			return false;
		}
	})	
	
	jQuery(window).resize(function(){
		if ($("#login-box").is(':visible')){
			reposLogin();
		}
			
	});
	jQuery(window).scroll(function(){
		if ($("#login-box").is(':visible')){
			reposLogin();
		}
			
	});
}

function reposLogin(){
	if (window.innerHeight) {
		_height = window.innerHeight;
		_width = window.innerWidth;
	} else {
		_height = document.documentElement.clientHeight;
		_width = document.documentElement.clientWidth;
	}
	var scrollTop = $(window).scrollTop();

	$("#login-box #back").css("width","100%") ;
	$("#login-box #back").css("height",$(document).height()) ;
	
	$("#login-box #inside").css("left",_width/2- $("#login-box #inside").width()/2) ;
	$("#login-box #inside").css("top",_height/2- $("#login-box #inside").height()/2 + scrollTop) ;
}

function closeLoginBox(){
	isFocused = false;
	if ($.browser.msie && $.browser.version.substr(0,1)<7) {
		$("select").show();
	}
	$("#login-form").unbind('submit');
	$("#create-form").unbind('submit');
	$("#login-box").hide();
}

// submit the login form
function submitLogin()
{
	email = $("#login-form #user").val();
	pwd = $("#login-form #pass").val();
	if (email == '' || pwd == '')
	{
		$("#error-msg span").empty();
		$("#error-msg span").append('Please enter both email and password');
		$("#error-msg").fadeIn();
	}
	else
	{
		$.getJSON(login_url, {username: email, password: pwd}, function(result){ checkLoginResult(result.status); });
	}
	
	return false;
}

// redirect or error
function checkLoginResult(result)
{
	if (result == 'success')
	{
		if (goto_page != '')
			location.href = goto_page;
		else
			location.reload();
	}
	else
	{
		$("#error-msg span").empty();
		$("#error-msg span").append('Error: the email and password do not match');
		$("#error-msg").show();
	}
}

// submit the create a new account form
function submitCreate()
{
	email = $("#create-form #user_create").val();
	pwd = $("#create-form #pass_create").val();
	repeat_pwd = $("#create-form #repeat_pass").val();
	
	$("#create-error-msg span").empty();
	if (email == '' || pwd == '' || repeat_pwd == '')
	{
		$("#create-error-msg span").append('Error: Please fill in all fields');
		$("#create-error-msg").fadeIn();
	}
	else if (pwd != repeat_pwd)
	{
		$("#create-error-msg span").append('Error: The passwords do not match');
		$("#create-error-msg").fadeIn();
	}
	else
	{
		$.getJSON('https://' + window.location.hostname + SITE_PATH + "index.php?c=member&m=create_account&callback=?", {username: email, password: pwd}, function(result){ checkCreationResult(result.status); });	
	}
	
	return false;
}

// redirect or error
function checkCreationResult(result)
{
	if (result == 'success')
	{
		if (goto_page != '')
			location.href = goto_page;
		else
			location.reload();
	}
	else if (result == 'exists')
	{
		$("#create-error-msg span").empty();
		$("#create-error-msg span").append('Error: the email is already taken');
		$("#create-error-msg").show();
	}
	else
	{
		$("#create-error-msg span").empty();
		$("#create-error-msg span").append('<div class="edit_error">'+result+'</div>');
		$("#create-error-msg").show();
		
	}
}


//*****************************************************************************************************************************/
//***************************************** TOOLTIP BY FRANCOIS ARBOUR AUG 21 2009 ********************************************/
//*****************************************************************************************************************************/

initToolTip = function(){	
		
	xOffset = 0;
	yOffset = 30;
	
	$(".tooltip").hover(function(e){
		$("body").append('<div id="tooltip"><div class="debug" style="color:#FFF"></div><div class="inside">This is content This is content</div></div>');								 
		$("#tooltip")
			.fadeIn("fast");
		$.ajax({
		  url: "/tooltips/mass_duplication.php",
		  cache: true,
		  success: function(html){
			$("#tooltip .inside").html(html);
		  }
		});
    },
	function(){
		$("#tooltip").remove();
    });	
	
	$(".tooltip").mousemove(function(e){
		
		
		var distX = $("#tooltip h2").offset().left;
		
		$("#tooltip")
			.css("left",(e.pageX-20) + "px")
			.css("top",(e.pageY+20) + "px");
			
		$("#tooltip .debug").html(distX);
		
		
	});
	
};

//*****************************************************************************************************************************/
//************************************** MODAL WINDOW BY FRANCOIS ARBOUR AUG 21 2009 ******************************************/
//*****************************************************************************************************************************/

initModalWindows = function(){	
	$('.modal').unbind('click');
	$(".modal").click(function(e){
		var url = $(this).attr("href");
		openModalWindow("ajax",url);
		return false;
    })
	
};

function openModalWindow(p_type, p_param){
	isFocused = true;
	$("body").prepend('<div id="modal"><div id="back"></div><div id="inside"><a href="#" id="close-bt">CLOSE</a><div id="content">Loading...</div></div></div>');
	
	$("#modal #back").fadeTo( 0, 0).fadeTo( 300, 0.6);
	$("#modal #inside").fadeTo( 0, 0).fadeTo( 300, 0).fadeTo( 300, 1);
	
	if(p_type == "ajax"){
		$("#modal #inside #content").load(p_param,
			function(html){
				reposModalWindow();
			}
		);
	}else if(p_type == "html"){
		$("#modal #inside #content").html(p_param);
		reposModalWindow();
	}
	
	reposModalWindow();
	
	$("#modal #back").click(function(){
		closeModalWindow();
		return false;
	})
	
	$("#modal #close-bt").click(function(){
		closeModalWindow();
		return false;
	})
	
	jQuery(window).resize(function(){
		if ($("#modal").is(':visible')){
			reposModalWindow();
		}
			
	});
	jQuery(window).scroll(function(){
		if ($("#modal").is(':visible')){
			reposModalWindow();
		}
			
	});
}

function reposModalWindow(){
	if (window.innerHeight) {
		_height = window.innerHeight;
		_width = window.innerWidth;
	} else {
		_height = document.documentElement.clientHeight;
		_width = document.documentElement.clientWidth;
	}
	var scrollTop = $(window).scrollTop();
	
	$("#modal #back").css("width","100%") ;
	$("#modal #back").css("height",$(document).height()) ;
	
	var scrollTop = $(window).scrollTop();
	var l = _width/2- $("#modal #inside").width()/2;
	var t = _height/2- $("#modal #inside").height()/2+scrollTop;
	
	$("#modal #inside").css("left",l);
	$("#modal #inside").css("top",t);
}

function closeModalWindow(){
	isFocused = false;
	$("#modal").remove();
}

$(document).ready(function(){					   
	initModalWindows();
})


//*****************************************************************************************************************************/
//**************************************** SITE INIT BY FRANCOIS ARBOUR OCT 9 2009 ********************************************/
//**************************************** MODIFS MK 17 DEC 2009                   ********************************************/
//*****************************************************************************************************************************/


$(document).ready(function(){ 
	
	jQuery(document).pngFix();
	enablePreviews();
	
	// add or remove a song from the favorites
	
	$(".btn-add, .favorites-link-add").click(function(){
		addToFav($(this));
		return false;
	});

	$(".btn-add, .favorites-link-add").each(function(){
		$(this).find('img').css("opacity","0.4")
	});
	
	$(".btn-add, .favorites-link-add").mouseover(function(){
		$(this).find('img').css("opacity","1")
		return false;
	});
	
	$(".btn-add, .favorites-link-add").mouseout(function(){
		$(this).find('img').css("opacity","0.4")
		return false;
	});
	
	$("#login-bt").click(function(){
		  openLoginBox('');
	})
	
	$("#your-account-bt").click(function(){
		  openLoginBox('/member');
	})
	
	$("#bt-get-notified").bind("click",function(){
		$("#get-notified").toggle();		
		return false;
	})
	
});

//*****************************************************************************************************************************/
//**************************************** SEARCH FUNCTION BY MAURICE KHERLAKIAN 29 oct 2009 **********************************/
//*****************************************************************************************************************************/
//The following functions rewrite a search query before sending it to the server.
//They're enclosed in a namespace to avoid collisions.
if(typeof(PB) == 'undefined')
	PB = {};
PB.search = {};
PB.search = function() {
	function urlencode (str) {
		str = escape(str);
		return str.replace(/[*+\/@]|%20/g,
		function (s) {
		switch (s) {
		case "*": s = "%2A"; break;
		case "+": s = "%2B"; break;
		case "/": s = "%2F"; break;
		case "@": s = "%40"; break;
		case "%20": s = "+"; break;
		}
		return s;
		});
	}
	
	return {
		submit_search_form: function(type) {
		  var search_text = urlencode($("#search_text").val());
			if(search_text == "Search"){
				search_text = '';
			}
		  var include_classical = '';
		  if(type == null) type='song';

		  if($('#include_classical').length == 0) include_classical = '/classical/ns';
		  else {
			  include_classical = $('#include_classical').attr('checked') ? '/classical/y':'/classical/n';
		  }

		  if (search_text != '')
		  {
			 
			  if(type == 'song') {
				  document.location.href = SITE_PATH + "royalty_free_music/search/" + search_text + include_classical;
			  } else {
				  document.location.href = SITE_PATH + "search/index_sfx/" + search_text;
			  }
		  }	  
		  return false;
		}
	}
} ();



$(document).ready(function(){					   
//	$('#include_classical').bind('click', PB.search.submit_search_form);
	$('#include_classical').bind('click', function() {
		PB.search.submit_search_form('song');
	});
	$('#subscribe_text').focus(function(){
		if($(this).attr('value') == 'Enter email'){
			$(this).attr('value','');
		}
	});
	
	$('#subscribe_text').blur(function(){
		if($(this).attr('value') == ''){
			$(this).attr('value','Enter email');
		}
	});
	
	$('.media-players-promo div').click(function(){
		document.location = "/flash_media_players";
	});
	
	$('.browseby div #search_text').focus(function(){
		
		if($('.browseby div #search_text').val() == "Search"){
			$(this).val("");
		}
		
		$("body").mousedown(function(){
			$(this).unbind("mousedown");
			$(document).unbind("keydown");
			if($('.browseby div #search_text').val() == ""){
				$('.browseby div #search_text').val("Search");	
			}
		})
		
		$(document).keydown(function(e){
			if (e.keyCode == 13) { 
				PB.search.submit_search_form();
			}
		});
		
		
	});
	
	$('#search_text').focus(function(){
		
		if($('#search_text').val() == "Search"){
			$(this).val("");
		}
		
		$("body").mousedown(function(){
			$(this).unbind("mousedown");
			$(document).unbind("keydown");
			if($('.browseby div #search_text').val() == ""){
				$('.browseby div #search_text').val("Search");	
			}
		})
		
		$(document).keydown(function(e){
			if (e.keyCode == 13) { 
				if($('#search_text').attr('rel') == 'sfx'){
					PB.search.submit_search_form('sfx');
					
				}else{
					PB.search.submit_search_form();	
				}
				return false;
			}
			
		});
		
		
	});

})




