var FBinitialized = 0;
var disableAlbumSettingsPanelThemePreview = false;
var horizontalTabs = false;
var QpRequest;

$( document ).ready(function()
{
	if( !getCookie("sessionTransfered") )
	{
		jQuery.getScript( domainName + "/requestsession.seam?customdomain=" +location.host);
	}
});


function hideAndGetNewMessage()
{
	showMainLoading("Loading new message");

	var parameters = [{ "name": "method", "value": "bluemelon.users.hidelastmessage" }];

	$.post( "/api/ajax/", parameters, function( xml ){
		$( xml ).find( 'rsp' ).each( function(){
			if( $(this).attr( 'status' ) != 'ok' )
			{
				//error	
				hideMainLoading();
				alert( "The changes are not saved: " + $( this ).attr( 'errormsg' ));
				return;
			}
			else
			{	
				//status = OK
				
				//GET NEW message, if exist
				parameters = [{ "name": "method", "value": "bluemelon.users.getlastmessage" }];
				
				$.post( "/api/ajax/", parameters, function( xml ){
					$( xml ).find( 'rsp' ).each( function(){
						if( $(this).attr( 'status' ) != 'ok' )
						{
							//error	
							hideMainLoading();		
							alert( "The changes are not saved: " + $( this ).attr( 'errormsg' ));
		
							//hide message box
							$( "div.instantMessages" ).fadeOut( "slow" );
							return;
						}
						else
						{	
							//status = OK
							hideMainLoading();
							
							//test if next message is null
							if ( $(this).find( 'text' ).length == 0 )
							{	//test if attribute 'text' exist ( not for his length!!! )
								
								//hide message box
								$( "div.instantMessages" ).fadeOut( "slow" );
								return;
							}
							
							var newText = $(this).find( 'text' ).text();
							var newFromUser = $(this).find( 'fromUserLogin' ).text();
							$( "div.instantMessages" ).fadeOut( "fast", function () 
							{	//run after fadeOut finish
								$( "div.instantMessages" )[0].innerHTML = "Message from " + newFromUser + " : " + newText + " [<a href='javascript:hideAndGetNewMessage();' class='hideMessage' >Hide</a>]";
								$( "div.instantMessages" ).fadeIn( "fast" );	
				      });
						}
					});
				});
			}
		});
	});
}

function showQuickPanel( panelWidth )
{
	$( ".quickPanel" ).css( "position", "absolute");
	//set custom width
	if( panelWidth != null )
	{
		$(".quickPanel").css( "width", panelWidth );
		$(".quickPanel").css( "margin-left", -1 * panelWidth / 2 );
		
	}
	$( ".quickPanel" ).css( "top", $(window).scrollTop() + 70 );
	
	//show panel and background
	$( ".quickPanel" ).fadeIn("fast");
	$( ".quickPanelBack" ).css( "opacity", 0.7 );	
	$( ".quickPanelBack" ).fadeIn("fast");
	
	//if panel is very long, then show scrollbar
	//max height of quick panel is 500, if is need more space, then scrollbar is displayed
	if ( $(".quickPanelContent").height() > 500 )
		$(".quickPanelContent").height(500);
	else
	{
		$(".quickPanelContent").css( "height", "auto" );
	}
}

function showQuickPanelPreload( panelWidth, QpTitle )
{
	$( ".quickPanel" ).html( $( ".quickPanelPreload" ).html() );
	if( QpTitle != null )
	{
		$( ".quickPanel .quickPanelTitle" ).html(QpTitle);
	}
	showQuickPanel( panelWidth );
}

function abortQuickPanel()
{
	QpRequest.abort();
	hideQuickPanel();
	hideMainLoading();
}

function hideQuickPanel( hideBack )
{
	if( hideBack == null || hideBack == 1 )
	{
		$( "div.quickPanelBack" ).stop();	//if animation is in progress, stop
		$( "div.quickPanelBack" ).fadeOut( "fast", function(){
			//this opacity is also used in quick-panel-albumview.js
			$( this ).hide();
			$( this ).css( "opacity", 0.7 );	//because stop() was called, set to original value
		});
	}
	
	$( "div.quickPanel" ).fadeOut("fast", function(){
		$(this).hide();
		$(this).css( "top", "auto" );
	});
}

function showMainLoading( msg )
{
	$("#mainLoading").html("<span class='loadingContainer'>"+msg+"</span>");

	//img.logo might not exist, if power user displays his/her own logo
	if( $("img.logo").offset() == null )
	{
		$( "#mainLoading" ).css({
		'left': 52
		});
	}
	else
	{
	$( "#mainLoading" ).css({
		'left': $("img.logo").offset().left + 52
	});
	}

	$("#mainLoading span").fadeIn("fast");
}

function hideMainLoading()
{
	// stop loading image
	setTimeout('$("#mainLoading span").fadeOut("slow");', 1000);
}

function showAlbumPanel( folderId, boolThemePreview )
{
	disableAlbumSettingsPanelThemePreview = boolThemePreview;
	showQuickPanelPreload( 755, "Loading album settings panel..." );
	
	var url_parameters = urldecode( $( "#url_parameters" ).text() + "&folderid=" + folderId + "&" );
	QpRequest = $.get( "/snippets/album-settings-panel.inc.seam", url_parameters, function( data, status )
	{
		if( status != "success" )
		{
			//error
			alert( "Error loading Album Panel: " + $(this).attr( 'errormsg' ));
			hideQuickPanel();
			return;
		}
		$( ".quickPanel" ).html( data );
		// stop loading image
		showQuickPanel( 755 );
	});
}

function showGoToAlbumPanel( userId, folderId, catId )
{
	var params = new Array();
	params.push( { "name": "userid", "value": userId } );
	if ( folderId > 0 )
	{
		params.push( { "name": "folderid", "value": folderId } );
	}
	
	if ( catId > 0 )
	{
		params.push( { "name": "categoryid", "value": catId } )
	}
	
	showQuickPanelPreload( 500, "Loading Go to Album panel..." );
	
	QpRequest = $.get( "/snippets/change-album-treeview.inc.seam", params, function( data, status )
	{
		if( status != "success" )
		{
			//error
			alert( "Error loading Go to Album Panel: " + $(this).attr( 'errormsg' ));
			hideQuickPanel();
			return;
		}
		$( ".quickPanel" ).html( data );
		//$( "#loading" ).hide();	//must be commented, because it hide "loading" in wrong time
		//and therefore dont show "loading" while construct tree
		
		showQuickPanel(500);
	});
}


function showShareInvitations()
{
	var snippetParameters = "";
	
	if( typeof(actualView) != "undefined" && actualView == "item"  )
	{//itemView
		snippetParameters = "?folderid=" + loaded_folderId + "&itemid=" + actualItemId;
	}
	else if ( typeof( loaded_folderId ) != "undefined"  )
	{//AlbumView
		snippetParameters = "?folderid=" + loaded_folderId;
	}
	else
	{//homePage
		snippetParameters = "?userid=" + $( "#userId" ).text();
	}
	
	showQuickPanelPreload( 850, "Loading Invitation panel..." );
	QpRequest = $.get( "/snippets/share-quickpanel-invitations.inc.seam"+snippetParameters, function( data, status )
	{
		if( status != "success" )
		{
			//error
			alert( "Error loading Send an Email: " + $(this).attr( 'errormsg' ));
			return;
		}
		$( ".quickPanel" ).html( data );
		showQuickPanel(850);
	});
	
}

function showShareGetLinks()
{
	if( typeof(actualView) != "undefined" && ( actualView == "item" || actualView.indexOf( "combined" ) === 0 ) )
	{//itemView
		//there are two getlinks panel
		$( "#itemPanel div[id='fragment-2']" ).html( $( "#albumViewBase div[id=shareGetLinksPanel] .quickPanelContent" ).html() );
		$( ".quickPanel" ).html( $("#itemPanel > div[id=shareGetLinksPanel]").html() );
		showQuickPanel( 545 );
	}
	else if( typeof(actualView) != "undefined" && actualView != "item"  )
	{
		$( ".quickPanel" ).html( $("#albumViewBase div[id=shareGetLinksPanel]").html() );
		showQuickPanel( 535 );
	}
	else
	{
		$( ".quickPanel" ).html( $("div[id=shareGetLinksPanel]").html() );
		showQuickPanel( 535 );
	}
	if( typeof initVerticalTabs == 'function') { 
		initVerticalTabs();
	}
}

function showShareOnFacebook()
{
	if( $( "#itemPanel #shareGetLinksPanel span#publicAccess" ).text().length != 0 )
	{
		alert("This photo is not public and as such cannot be viewed by others");
		return;
	}
	
	var snippetParameters = "";
	
	if( typeof(actualView) != "undefined" && ( actualView == "item" || actualView.indexOf( "combined" ) === 0 ) )
	{//itemView
		snippetParameters = "?folderid=" + loaded_folderId + "&itemid=" + actualItemId;
	}
	else if ( typeof( loaded_folderId ) != "undefined"  )
	{//AlbumView
		snippetParameters = "?folderid=" + loaded_folderId;
	}
	else
	{//homePage
		snippetParameters = "?userid=" + $( "#userId" ).text();
	}
		
	showQuickPanelPreload( 400, "Loading Facebook panel..." );
	QpRequest = $.get( "/snippets/share-quickpanel-facebook.inc.seam"+snippetParameters, function( data, status )
	{
		if( status != "success" )
		{
			//error
			alert( "Error loading Facebook panel: " + $(this).attr( 'errormsg' ));
			return;
		}
		$( ".quickPanel" ).empty();
		$( ".quickPanel" ).html( data );
		//this is in share-facebook.js
		//showQuickPanel(400);
		//hideMainLoading();
	});
}

function showShareOnTwitter()
{
	if( $( "#itemPanel #shareGetLinksPanel span#publicAccess" ).text().length != 0 )
	{
		alert("This photo is not public and as such cannot be viewed by others");
		return;
	}
	
	var snippetParameters = "";
	
	if( typeof(actualView) != "undefined" && ( actualView == "item" || actualView.indexOf( "combined" ) === 0 ) )
	{//itemView
		snippetParameters = "?folderid=" + loaded_folderId + "&itemid=" + actualItemId;
	}
	else if ( typeof( loaded_folderId ) != "undefined"  )
	{//AlbumView
		snippetParameters = "?folderid=" + loaded_folderId;
	}
	else
	{//homePage
		snippetParameters = "?userid=" + $( "#userId" ).text();
	}
	
	showQuickPanelPreload( 400, "Loading Twitter panel..." );	
	QpRequest = $.get( "/snippets/share-quickpanel-twitter.inc.seam"+snippetParameters, function( data, status )
	{
		if( status != "success" )
		{
			//error
			hideMainLoading();
			alert( "Error loading Twitter panel: " + $(this).attr( 'errormsg' ));
			return;
		}
		$( ".quickPanel" ).html( data );
		//this is in share-twitter.js
		//showQuickPanel(400);
		//hideMainLoading();
	});
}

function showShareSocial()
{
	if( $( "#itemPanel #shareGetLinksPanel span#publicAccess" ).text().length != 0 )
	{
		alert("This photo is not public and as such cannot be viewed by others");
		return;
	}
	
	var sharedUrl = "";
	var sharedTitle = "";
	
	if( typeof(actualView) != "undefined" && actualView == "item" )
	{//itemView
		var imgObject = itemList.find( "item[id='"+actualItemId+"']" );
		sharedUrl = "http://www.bluemelon.com/"+$("#userUrl").text()+"/"+$("#folderUrl").text()+"/photo/"+actualItemId+"/"+$("#itemSubviewExt").text();
//		sharedUrl = "http://www.bluemelon.com/"+$("#userUrl").text()+"/"+$("#folderUrl").text()+"#photo-"+actualItemId+"/"+$("#itemSubviewExt").text();
		sharedTitle = imgObject.attr('title');
	}
	else if ( typeof( loaded_folderId ) != "undefined"  )
	{//AlbumView
		sharedUrl = "http://www.bluemelon.com/"+$("#userUrl").text()+"/"+$("#folderUrl").text();
		sharedTitle = $("title").text();
	}
	else
	{//homePage
		sharedUrl = "http://www.bluemelon.com/"+$("#userUrl").text();
		sharedTitle = "user's homepage"
	}
	
	$("#shareAddThisPanel .quickPanelContent").css("padding-left","40px");
	
	$("#shareAddThisPanel .quickPanelContent").html("<iframe src ='/snippets/share-quickpanel-addthis.inc.seam?sharedUrl="+sharedUrl+"&sharedTitle="+sharedTitle+"' width='305' height='375' frameborder='0'></iframe>");
	$("#shareAddThisPanel .quickPanelContent").css( "overflow", "hidden" );
	$( ".quickPanel" ).html( $("#shareAddThisPanel").html() );
	
	showQuickPanel(400);
}

function setCookie( name, value, expires, path, domain, secure )
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

// this deletes the cookie when called
function deleteCookie( name, path, domain ) 
{
	if ( getCookie( name ) )
	{
		document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
}

// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

function createBuyMenu()
{
	//create last used menu
	var cookieValue = getCookie("lastProducts");
	
	if(cookieValue != null)
	{
		//show menu header
		$(".lastUsedProductMenu").show();
		
		//erase old menu Item
		$(".lastUsedProductMenuItem").remove();
		
		cookieValue = cookieValue.substring( 1, cookieValue.length - 1 ); //remove "

		//cookie format is "7:EZPRINTS:4x6 Glossy print:0.59|14:EZPRINTS:5x7 Glossy print:2.65"
		var lastUsedProducts = cookieValue.split("|");
		var menuSourceAlbumView = "";
		var menuSourceItemView = "";
		var folderId = loaded_folderId;
		
		$(lastUsedProducts).each(function(){
				var productInfo = this.split(":");
				var productId = productInfo[0];
				var productProvider = productInfo[1];
				var productName = unescape(productInfo[2]);
				productName = productName.replace( /\\\"/g, "\"" );
				var productPrice = productInfo[3];
				menuSourceAlbumView = menuSourceAlbumView + "<li class='lastUsedProductMenuItem'><a href='javascript:buyAlbumProduct( " + productId + ", &quot;"+ productProvider +"&quot;, "+folderId+" );'>"+productName+" [$"+productPrice+"]</a></li>";
				menuSourceItemView = menuSourceItemView + "<li class='lastUsedProductMenuItem'><a href='javascript:buyItemProduct( " + productId + ", &quot;"+ productProvider +"&quot; );'>"+productName+" [$"+productPrice+"]</a></li>";
		});
		
		$("li[id=albumViewLastUsedProductMenu]").after( menuSourceAlbumView );
		$("li[id=itemViewLastUsedProductMenu]").after( menuSourceItemView );
		
		//for itemView side panel
		$("table.toolsPanelPhotos ul.down-list").each(function(){
			$(this).css( "left", -1*( $(this).width() + 10 ) );
			$(this).css( "top", "1px" );
		});
	}
}

function dismissGlobMsg()
{
	$('ul.globalMessages').fadeOut('slow');
}

function URLDecode( string )
{
	try// just in case there were some encoding errors such as the presence of <WBR/> in between code characters
	{
		string = decodeURIComponent( string.replace( /<WBR\/>/g, '' ).replace( /\+/g, '%20' ) );
	}
	catch( error )
	{
	}
	return string;
}