var userInfo=new Object();
var siteColor={lightGrey:'#9298aa',middleGrey:'#43424f',darkGrey:'#33323a',white:'#ffffff',black:'#000000'};
var browserCap=new Object();
var gotoContent=new Array();
var gotoBookmark=0;
var gotoLimit=0;
var gotoLastPageNo;
var gotoCurrentPageNo=0;
var gotoNext=true;
var gotoPrevious=false;
var currentPage=window.location;
var siteActivePages=['index.html','news.html','appearances.html','biography.html','discography.html','gallery.html','press.html','guestbook.html'];
var BubbleObject;
var editable=false;
var browser=new Object();
var reloadPage
var dynamicColor;
var refresh=false;


function buttonBehavior(button,className,action){
	if(action=='hover'){
		$(button).css("cursor","pointer");
		$(button).addClass(className);
	}
	if(action=='leave'){
		$(button).removeClass(className);
	}	
}

function glowingBackground(button,firstColor){
	$(button).animate({ 'background-color': firstColor}, 500);	
}

var activeOptionButton=false;
function activeOption(button,className,keepPrevious){
		$(button).addClass(className);
		//inactivate previous button
		if(activeOptionButton && !keepPrevious){
			$(activeOptionButton).removeClass(className);
		}
		//set new active button
		activeOptionButton=button;
}
var pages={'index.html':'home','news.html':'news','appearances.html':'appearances','biography.html':'biography','discography.html':'discography','gallery.html':'gallery','press.html':'press','guestbook.html':'guestbook'};
var currentPage=document.location.href.split("/")[3];
var menuItem;

$(document).ready(function(){
	//bottom menu functionality
	$('.footerItem').hover(
		function(){
			buttonBehavior(this,'buttonMouseOver','hover');
		},
		function(){
			buttonBehavior(this,'buttonMouseOver','leave');
		}
	)
	$('.footerItem').click(function(){
		var content=new Object();
		var id=$(this).attr('id');
		if(!id){
			return;
		}else{
			if(id=='links'){
				content.title="Links"
			}else if(id=='privacy'){
				content.title="Privacy Policy"		
			}else if(id=='rights'){
				content.title="Rights"		
			}
			//{title:"News Editor"};
			createPopUpWindow(id,content, 500);		
		}

	})

	//check if user is looged in session
	checkLoginUser()

// ============================ 
// ! go home shortcut on logo   
// ============================ 
	var location=window.location.href.split("/")[2];
	//$('#logo>img').wrap('<a style="border:none;outline:none;" href="http://'+location+'">');

// =========================================== 
// ! mouse over behavior for glowing buttons   
// =========================================== 

	$('.glowingButton').hover(
		function(){
			buttonBehavior(this,'buttonMouseOver','hover');
			glowingBackground(this,'#33323a');
		},
		function(){
			buttonBehavior(this,'buttonMouseOver','leave');
			glowingBackground(this,'#9298aa');
		}
	)
	
// =================== 
// ! top menu actions  
// =================== 
		
	if(!currentPage){
		currentPage='index.html';
	}
	$.each(pages,function(location,button){
		if(location==currentPage){
			$('#'+button).addClass('activePage');
			menuItem=button;			
		}
		
	})
	
	$('#leftTopMenu>#gallery').hover(
		function(){
			if(currentPage!='gallery.html'){
				$(this).css('position','relative');
				$(this).html('<span style="color:white">gallery</span><p id="stage" class="tSub">stage</p><p id="portraits" class="tSub">portraits</p><p id="inprint" class="tSub">inprint</p><p id="personal" class="tSub">personal</p><p id="artwork" class="tSub">artwork</p><p id="video" class="tSub">video</p><p id="audio" class="tSub">audio</p>');
					$('.tSub').hover(
						function(){
							$(this).css('color','white')
						},
						function(){
							$(this).css('color',dynamicColor)
						}
				)
				$('.tSub').click(function(){
					
					if($(this).attr('id')=='audio'){
						localStorage['openMusicPlayer']="on";
					}else{
						localStorage['openGallerySection']=$(this).attr('id');
					}
					
				})
				$(this).animate({height:'+=215'},300)			
			}
		},
		function(){
			if(currentPage!='gallery.html'){
				$(this).animate({height:'-=215'},100)
				$(this).html('gallery')
			}	
		}
	)
	
	$('#leftTopMenu>#appearances').hover(
		function(){
			if(currentPage!='appearances.html'){
				$(this).css('position','relative');
				$(this).html('<span style="color:white">appearances</span><p id="all" class="tSub">all</p><p id="opera" class="tSub">opera</p><p id="concerts" class="tSub">concerts</p>');
					$('.tSub').hover(
						function(){
							$(this).css('color','white')
						},
						function(){
							$(this).css('color',dynamicColor)
						}
				)
				$('.tSub').click(function(){
					localStorage['openAppearancesSection']=$(this).attr('id');
				})
				$(this).animate({height:'+=92'},300)			
			}
		},
		function(){
			if(currentPage!='appearances.html'){
				$(this).animate({height:'-=92'},100)
				$(this).html('appearances')
			}	
		}
	)
	
	$('#leftTopMenu>#discography').hover(
		function(){
			if(currentPage!='discography.html'){
				$(this).css('position','relative');
				$(this).html('<span style="color:white">discography</span><p id="CD" class="tSub">CD</p><p id="DVD" class="tSub">DVD</p><p id="opera" class="tSub">opera</p><p id="solo" class="tSub">solo</p><p id="compilations" class="tSub">compilations</p>');
					$('.tSub').hover(
						function(){
							$(this).css('color','white')
						},
						function(){
							$(this).css('color',dynamicColor)
						}
				)
				$('.tSub').click(function(){
					localStorage['openDiscographySection']=$(this).attr('id');
				})
				$(this).animate({height:'+=155'},300)			
			}
		},
		function(){
			if(currentPage!='discography.html'){
				$(this).animate({height:'-=155'},100)
				$(this).html('discography')
			}	
		}
	)	

	$('#leftTopMenu>#press').hover(
		function(){
			if(currentPage!='press.html'){
				$(this).css('position','relative');
				$(this).html('<span style="color:white">press</span><p id="reviews" class="tSub">reviews</p><p id="interviews" class="tSub">interviews</p><p id="releases" class="tSub">releases</p>');
					$('.tSub').hover(
						function(){
							$(this).css('color','white')
						},
						function(){
							$(this).css('color',dynamicColor)
						}
				)
				$('.tSub').click(function(){
					localStorage['openPressSection']=$(this).attr('id');
				})
				$(this).animate({height:'+=92'},300)			
			}
		},
		function(){
			if(currentPage!='press.html'){
				$(this).animate({height:'-=92'},100)
				$(this).html('press')
			}	
		}
	)

	
	$('#leftTopMenu>div').click(function(){		
			var pageName=$(this).attr('id');
			//check if music player is set for opening
			if(pageName=='gallery'){
				if(localStorage['openMusicPlayer']=="on"){
					openPlayList();
					localStorage.removeItem('openMusicPlayer');
					return;					
				}
			}
			
			if(pageName!=menuItem){		
				if(pageName=='home'){
					window.location='index.html';			
				}else if(pageName=='contact'){
					setUpWindow('iconEmail')
				}else{
					window.location=pageName+'.html';
				}
			}else{
				return;
			}		
	
	})
	
// ====================== 
// ! handle ajax errors   
// ====================== 


	$.ajaxSetup({
		error:function(x,e){
			if(x.status==0){
			alert('You are offline!!\n Please Check Your Network.');
			}else if(x.status==404){
			alert('Requested URL not found.');
			}else if(x.status==500){
			alert('Internel Server Error.');
			}else if(e=='parsererror'){
			alert('Error.\nParsing JSON Request failed.');
			}else if(e=='timeout'){
			alert('Request Time out.');
			}else {
			alert('Unknow Error.\n'+x.responseText);
			}
		}
	});
	
// ========================= 
// ! add indexOf to arrays   
// ========================= 


if (!Array.prototype.indexOf){
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}
	
	//set globals
	setGlobals();
})

// =================== 
// ! create tooltips   
// =================== 

	function setInnerHtmlTooltip(element,value){
		element.SetBubblePopupInnerHtml(value);
		element.FreezeAllBubblePopups();
	}
	
	var optionsTooltips =	{ 
								themeName: 'black',
								themePath: 'plugins/jquerybubblepopup-theme/',
								width:250
					};
	


// =============== 
// ! format date   
// =============== 

function dateFormat(date,separator){
	var oldSeparator=date.substring(4,5);
	var dateElements=date.split(oldSeparator);
	var newDate=dateElements[0]+separator+dateElements[1]+separator+dateElements[2];
	return newDate;
}


function humanDate(date,reverse){
	if(!date){
		return;
	}
	var elements;
	var newDate;
	var month=Array('none','January','February','March','April','May','June','July','August','September','October','November','December');
	if(!reverse){
		if(date.indexOf('-')==-1){
			return;
		}
		elements=date.split('-');
		if(!Number(elements[0]) && !Number(elements[1]) && !Number(elements[2])){
			newDate='';
		}else if(!Number(elements[1]) || !Number(elements[2])){
			newDate=Number(elements[0]); 
		}else if(date.indexOf(':')==-1){
			newDate=month[Number(elements[1])]+' '+elements[2]+', '+elements[0];
		}else{
			var time=elements[2].split(' ');
			newDate=month[Number(elements[1])]+' '+time[0]+', '+elements[0]+' - '+time[1];
		}
	}else{
		elements=date.split(' ');
		var elMonth=elements[0];
		if(elements){
			var elDay=elements[1].slice(0, -1);
		}
		var elYear=elements[2];
		newDate=elYear+'-'+month.indexOf(elMonth)+'-'+elDay;
	}
	
	return newDate;
}

function characterIs(character){
	if(isNaN(character*1)){
		return 'number';
	}
	
	if(character == character.toUpperCase()){
		return 'upper case';
	}
	
	if(character == character.toLowerCase()){
		return 'lower case';
	}
}

function unifiedDate(dates){
	
	var datesArray=new Array();
	var years=new Array()
	var months=new Object()
	var all=new Array()
	var monthHuman=Array('none','January','February','March','April','May','June','July','August','September','October','November','December');
	var compoundDate;
	
	jQuery.each(dates, function(i){
		var date=String(dates[i]).split('-')		
		datesArray.push(Array(date[0],date[1],date[2]));
	})
	
	jQuery.each(datesArray, function(index){
		years.push(datesArray[index][0]);
		years=uniqueArray(years);
	})
	
	jQuery.each(datesArray, function(index){
		jQuery.each(years,function(i,v){	
			var yearMark=v;
			if(jQuery.inArray(yearMark,all)<0){
				all.push(yearMark);			
			}
	
			if(datesArray[index][0]==v){
				var month=monthHuman[Number(datesArray[index][1])];
				if(jQuery.inArray(month,all)<0){
					all.push(monthHuman[Number(datesArray[index][1])]);
				}				
				all.push(datesArray[index][2]+',');
			}
		})
		
	})
		compoundDate=all.join(' ');
		
		return (compoundDate.slice(0,-1));
		//return dates;
		
	}

// ======================= 
// ! create modal window   
// ======================= 

function createPopUpWindow(type,content,width,height){
	//freeze pop up bubbles
	if(BubbleObject){
		BubbleObject.HideAllBubblePopups()
		BubbleObject.FreezeAllBubblePopups();
	}	
	
	//set options
	if(!height){
		modalHeight='auto';
	}else{
		modalHeight=height;
	}
	
	if(!width){
		modalWidth='500';
	}else{
		modalWidth=width;
	}
	
	$('#modalWin').remove();
	$('#allContent').append('<div id="modalWin"></div>');
	//format content according to type
// ======== 
// ! news   
// ======== 

	if(type=='news'){
		$('#modalWin').html(
			'<div class="modalNewsDate">'+content.date+'</div><div class="modalNewsMessage">'+content.message+'</div>'
		);
// =============== 
// ! appearances   
// =============== 

	}else if(type=='appearances'){
		$('#modalWin').html(
			'<p><span class="modalAppearancesInfoType">dates: </span><span class="modalAppearancesInfo">'+unifiedDate(content.date)+'</span></p><p><span class="modalAppearancesInfoType">location: </span><span class="modalAppearancesInfo">'+content.info.location+', '+content.info.country+'</span></p><p><span class="modalAppearancesInfoType">venue: </span><span class="modalAppearancesInfo"><a class="modalTextLink" target="_blank" href="'+content.info.venueLink+'">'+content.info.venue+'</a></span></p><p><span class="modalAppearancesInfoType">orchestra: </span><span class="modalAppearancesInfo"><a class="modalTextLink" target="_blank" href="'+content.info.orchestraLink+'">'+content.info.orchestra+'</a></span></p><p><span class="modalAppearancesInfo"><div class="modalLine"></div><div class="modalButtonEnclosure"><p><span class="uiButton modalButton"><a class="modalButtonsLink" target="_blank" href="'+content.info.detailsLink+'">more info</a></span></p><p><span class="uiButton modalButton"><a class="modalButtonsLink" target="_blank" href="'+content.info.bookingLink+'">booking</a></span></p></div>'
		);
// =========== 
// ! contact   
// =========== 

	}else if(type=='contact'){
		$('#modalWin').html(content.info);
// ========= 
// ! album   
// ========= 

	}else if(type=='album'){
		var trackList='';
		var audioFiles=''
		if(content.tracks){
			for(i=0;i<content.tracks.length;i++){
				trackList+='<li id="'+content.tracks[i].id+'" class="modalAlbumTrack"><span id="track_'+content.tracks[i].id+'" class="modalPlayerIcon ui-icon ui-icon-volume-off"></span><span id="trackName_'+content.tracks[i].id+'" class="justBold">'+content.tracks[i].trackName+'</span><br><span> by '+content.tracks[i].composer+'</span><span id="time_'+content.tracks[i].id+'"> (sample)</span></li>';			
			}
		}	
		$('#modalWin').html('<div class="modalAlbumContainer"><img class="modalAlbumPicture" src="'+content.info.picture+'"/><div class="modalAlbumDetails"><li class="modalAlbumDetailsList"><span class="justBold">Artists: </span>'+content.info.artists+'</li><li class="modalAlbumDetailsList"><span class="justBold">Composer: </span>'+content.info.composer+'</li><li class="modalAlbumDetailsList"><span class="justBold">Orchestra: </span>'+content.info.orchestra+'</li><li class="modalAlbumDetailsList"><span class="justBold">Conductor: </span>'+content.info.conductor+'</li><li class="modalAlbumDetailsList"><span class="justBold">Producer: </span>'+content.info.producer+'</li><li class="modalAlbumDetailsList"><span class="justBold">Catalog: </span>'+content.info.catalog+'</li><div class="modalAlbumBuyButtons"><div class="modalAlbumButtonsEnclosure"><div class="uiButton modalButton modalAlbumButton"><a  class="modalButtonsLink" href="'+content.info.amazonLink+'" target="_blank">buy from Amazon</a></div><div class="uiButton modalButton modalAlbumButton"><a  class="modalButtonsLink" href="'+content.info.iTunesLink+'" target="_blank">buy from iTunes</a></div></div></div></div><div class="modalAlbumTrackContainer">'+trackList+'</div></div>');
		//adjust track container according with samples number
		if(!content.tracks){
			$('.modalAlbumTrackContainer').remove();
			$('.modalAlbumContainer').height('200');
		}else if(content.tracks.length==1){
			$('.modalAlbumTrackContainer').height('50');
			$('.modalAlbumContainer').height('260');
		}else if(content.tracks.length==2){
			$('.modalAlbumTrackContainer').height('100');
			$('.modalAlbumContainer').height('310');
		}
// ============= 
// ! guestbook   
// ============= 

	}else if(type=='guestbook'){
		$('#modalWin').html('<div class="modalGuestBookContainer"><br><span class="contact">Name:</span><br><br><input type="text" size="25" id="guestbookName"><br><br><span class="contact">Email:</span><br><br><input type="text" size="25" id="guestbookEmail"><br><br><span class="contact">Country:</span><br><br><input type="text" size="25" id="guestbookCountry"><br><br><span class="contact">Message:</span><br><br><textarea id="guestbookMessage" name="message" rows="8" cols="60"></textarea><br><span class="modalGuestBookSubmitButton uiButton modalButton">Publish Your Message</span></div>');
		modalHeight=content.height;
	}else if(type=='press'){
// ========= 
// ! press  
// ========= 

		$('#modalWin').html('<div class="modalPressReadMore"><p class="justBold">'+content.info.author+'</p><div class="justHorizontalLine"></div><p>'+content.info.readMore+'</p><div class="justHorizontalLine"></div><p class="uiButton modalButton modalPressPDF">get PDF</p><p class="justItalic justAlignRight">'+content.info.releaseDate+'</p></div>');
	}
// ==============
// ! videoGallery   
// ==============
	
	else if(type=='videoGallery'){
		var gotoPlaylist=new goto(content.playlist,1);
		var currentVideoPosition;

		function videoSetUp(video){
		
			for (v=0;v<content.playlist.length;v++){
				if(content.playlist[v].id==video.id){
					//add 1 to make position equivalent with gotoPlaylist page number
					currentVideoPosition=v+1;
					break;
				}
			}
			gotoPlaylist.jumpToPage(currentVideoPosition);
		}	
		
		function changeVideo(content,action){
		
			if(action=='open'){
				$('#modalWin').html(
					'<div id="modalVideoContent"><div id="modalVideoLink">'+content.video.youtubeLink+'</div><div class="justCenterText"><span class="justBold">'+content.video.videoName+'</span><br>'+content.video.videoInfo+'</div></div><div class="modalArrowIconEnclosure"><span id="previousModalArrow" class="modalIcon modalArrowIcon ui-icon ui-icon-triangle-1-w"></span><span id="nextModalArrow" class="modalIcon modalArrowIcon ui-icon ui-icon-triangle-1-e"></span></div>'
				);
				
				videoSetUp(content.video);
				
				$('.modalArrowIcon').click(function(){
						if($(this).attr('id')=='nextModalArrow' && gotoPlaylist.gotoNext){
						changeVideo(gotoPlaylist.jumpToPage(currentVideoPosition+1)[0],'change')
					}else if($(this).attr('id')=='previousModalArrow' && gotoPlaylist.gotoPrevious){
						changeVideo(gotoPlaylist.jumpToPage(currentVideoPosition-1)[0],'change')
					}
				})
				
				$('.modalArrowIcon').hover(
					function(){
						if(($(this).attr('id')=='nextModalArrow' && gotoPlaylist.gotoNext) || ($(this).attr('id')=='previousModalArrow' && gotoPlaylist.gotoPrevious)){
							$(this).css('cursor','pointer');
							$(this).css('backgroundColor',dynamicColor)
						}else{
						
							return false;}
					},
					function(){
						$(this).css('cursor','default');
						$(this).css('backgroundColor',siteColor.middleGrey);
					}				
				)
			
			}else if(action=='change'){
				$('#modalWin > #modalVideoContent').html('<div id="modalVideoLink">'+content.youtubeLink+'</div><div class="justCenterText"><span class="justBold">'+content.videoName+'</span><br>'+content.videoInfo+'</div>');
				videoSetUp(content);
			}	
									
		}
		
		//event.stopImmediatePropagation()			
		$('#modalWin > #modalVideoContent').hide()
		//start hidden
				
		changeVideo(content,'open');
	}
// ================ 
// ! photoGallery   
// ================ 
	else if(type=='pictureGallery'){

		var gotoPlaylist;
		var currentPicturePosition;
		var playlist=content.playlist;
		var scale=false;
		
		if(playlist){
			gotoPlaylist=new goto(playlist,1);
		}
		
		function pictureSetUp(picture){
		
			for (w=0;w<playlist.length;w++){
				if(content.playlist[w].id==picture){
					//add 1 to make position equivalent with gotoPlaylist page number
					currentPicturePosition=w+1;
					break;
				}
			}
			gotoPlaylist.jumpToPage(currentPicturePosition);
		}
		//main function
		function changePicture(content,action){	
			var picture='/gallery/'+content.id+'.jpg';
			var author;
			var sliderIcons='';
			
				
			if((docWidth<770 || docHeight<780) & !scale){
				content.height/=1.3;
				content.width/=1.3;
				scale=true;	
			}
			
			if(content.author!=''){
				author='&copy;'+content.author;
			}else{
				author='';
			}

			
			if(action=='open'){
				var icons;
				if(editable){
					icons='<span id="pictureGalleryClose" class="ui-icon ui-icon-circle-close pictureGalleryBtn"></span><span id="pictureGalleryEdit" class="ui-icon ui-icon-pencil pictureGalleryBtn"></span><span id="pictureGalleryRemove" class="ui-icon ui-icon-trash pictureGalleryBtn"></span>';
				}else{
					icons='<span id="pictureGalleryClose" class="ui-icon ui-icon-circle-close pictureGalleryBtn"></span>';
				}
				
				$('#modalWin').html('<div class="modalPictureGalleryContent">'+icons+'<div class="pictureGalleryTitle"></div><div id="currentPicture"><img id="modalEditImage" class="modalPictureGalleryImage" width="'+content.width+'" height="'+content.height+'" src="'+picture+'" /><div class="modalGalleryPictureDescription"   id="pictureEditDescription">'+content.description+'</div><div id="pictureEditDate"  class="modalGalleryPictureEventDate">'+content.eventDate+'</div><div id="pictureEditAuthor" class="modalGalleryPictureAuthor">'+author+'</div></div><div class="modalArrowIconEnclosure"><span id="previousModalArrow" class="modalIcon modalArrowIcon ui-icon ui-icon-triangle-1-w"></span><span id="nextModalArrow" class="modalGalleryResetBtn modalIcon modalArrowIcon ui-icon ui-icon-triangle-1-e"></span></div><div id="pictureSlider"></div></div>');

				//set arrows
				$('.modalArrowIcon').click(function(event){							
					if($(this).attr('id')=='nextModalArrow' && gotoPlaylist.gotoNext){	
						changePicture(gotoPlaylist.jumpToPage(currentPicturePosition+1)[0],'change')				
					}else if($(this).attr('id')=='previousModalArrow' && gotoPlaylist.gotoPrevious){
						changePicture(gotoPlaylist.jumpToPage(currentPicturePosition-1)[0],'change')
					}
					event.stopImmediatePropagation();
				})
				
			//closeBtn
			$('.pictureGalleryBtn').hover(
				function(){
					$(this).css('cursor','pointer');
				}
			)
			$('#pictureGalleryEdit').click(function(){
				editPicture(content.id);
			})	
				
			$('#pictureGalleryRemove').click(function(){
				removePicture(content.id);
				$('#modalWin').dialog('close');
			})	
				
			$('#pictureGalleryClose').click(function(){
				$('#modalWin').dialog('close');
			})	
				
			//determine current picture position
			pictureSetUp(content.id);
			
			}else if(action=='change'){
				
				$('#modalWin > .modalPictureGalleryContent > #currentPicture').html('<img id="modalEditImage" class="modalPictureGalleryImage" width="'+content.width+'" height="'+content.height+'" src="'+picture+'" /><div class="modalGalleryPictureDescription" id="pictureEditDescription"  >'+content.description+'</div><div id="pictureEditDate"   class="modalGalleryPictureEventDate">'+humanDate(content.eventDate)+'</div><div id="pictureEditAuthor" class="modalGalleryPictureAuthor">'+author+'</div></div>');
				//determine current picture position
				pictureSetUp(content.id);
			}

		var sliderIcons='';
		var visibleIcons=0
		if(currentPicturePosition<playlist.length){
			for(p=0;p<3;p++){
				if(playlist[currentPicturePosition+p]){
					sliderIcons+='<img position="'+Number(currentPicturePosition+p)+'" class="pictureSliderIcon" src="/gallery/'+playlist[currentPicturePosition+p].id+'_thumb" width="120px" height="90px" alt="'+playlist[currentPicturePosition+p].description+'"/>';
					visibleIcons++;
				}
			}
		}
		
		$('.pictureSliderIcon').live('mouseover',
			function(event){
				$(this).css('cursor','pointer')
				event.stopImmediatePropagation();
			}			
		)
		
		$('.pictureSliderIcon').live('mouseout',
			function(event){
				$(this).css('cursor','default')
				event.stopImmediatePropagation();
			}
		)

		$('.pictureSliderIcon').live('click', function(event){
			changePicture(playlist[$(this).attr('position')],'change')
			event.stopImmediatePropagation();
		})

		//content enclosure css settings
		$('.modalPictureGalleryContent').css('width',content.width+'px');
		$('.modalPictureGalleryContent').css('height',(Number(content.height)+120)+'px');
		$('.modalPictureGalleryContent').css('background-color',siteColor.black);
		$('.modalPictureGalleryContent').css('position','relative');
		$('.modalPictureGalleryContent').css('left',((modalWidth-$('.modalPictureGalleryContent').width())/2)+'px');
		//$('.modalPictureGalleryContent').css('top',((modalHeight-$('.modalPictureGalleryContent').height()-40)/2)+'px');
		
		$('.modalArrowIconEnclosure').css('position','absolute');
		$('.modalArrowIconEnclosure').css('left',(($('.modalPictureGalleryContent').width()-$('.modalArrowIconEnclosure').width())/2)+'px');
		$('.modalArrowIconEnclosure').css('bottom','-30px');

		//picture slider 
		$('#pictureSlider').css('top','100px');
		$('#pictureSlider').css('width',(visibleIcons*128)+'px');
		var leftValue=($('.modalPictureGalleryContent').width()-$('#pictureSlider').outerWidth())/2;
		$('#pictureSlider').css('left',leftValue+'px');
		$('#pictureSlider').html(sliderIcons);
		
		//gallery title
		$('.pictureGalleryTitle').text(content.title)
	}

		changePicture(content,'open');

	}
// ====================
// ! photoGallery Edit
// ====================
	else if(type=='editPicture'){		
		var picture='/gallery/'+content.pictureName;
		var thumbnailSelection=new Object();
		var imageSelection;

		$('#modalWin').html('<div class="modalPictureGalleryContent"><img id="modalEditImage" class="modalPictureGalleryImage" width="'+content.pictureInfo.width+'" height="'+content.pictureInfo.height+'" src="'+picture+'" /><div class="modalGalleryPictureDescription" id="pictureEditDescription" contenteditable="true">'+content.pictureInfo.description+'</div><div id="pictureEditDate" class="modalGalleryPictureEventDate" contenteditable="true">'+content.pictureInfo.date+'</div><div id="pictureEditAuthor" class="modalGalleryPictureAuthor" contenteditable="true">'+content.pictureInfo.author+'</div><div class="modalArrowIconEnclosure"><span id="modalGallerySaveBtn" class="modalIcon ui-icon ui-icon-circle-check"></span><span id="modalGalleryResetBtn" class="modalGalleryResetBtn modalIcon ui-icon ui-icon-circle-close"></span></div></div>');
		
		//content enclosure css settings
		$('.modalPictureGalleryContent').css('width',content.pictureInfo.width+'px');
		$('.modalPictureGalleryContent').css('height',(Number(content.pictureInfo.height)+100)+'px');
		$('.modalPictureGalleryContent').css('background-color',siteColor.black);
		$('.modalPictureGalleryContent').css('position','relative');
		$('.modalPictureGalleryContent').css('left',((modalWidth-$('.modalPictureGalleryContent').width())/2)+'px');
		
		$('.modalArrowIconEnclosure').css('position','absolute');
		$('.modalArrowIconEnclosure').css('left',(($('.modalPictureGalleryContent').width()-$('.modalArrowIconEnclosure').width())/2)+'px')
		$('.modalArrowIconEnclosure').css('bottom','6px');

		//configure date
		$('#pictureEditDate').live('focusout',function (event){
			var date=$(this).text();
			var check=new checkDateFormat(date);
			if(check.enServer()){
				$(this).text(humanDate(date));
			}	
			event.stopImmediatePropagation();				
		})
		
		$('#pictureEditDate').live('focusin',function (event){
			var date=$(this).text();
			var check=new checkDateFormat(date);
			if(check.enHuman()){
				$(this).text(humanDate(date,true));
			}	
			event.stopImmediatePropagation();				
		})
		
		//configure date on ENTER and TAB
		$('#pictureEditDate').keypress(function (key){
			if(key.which==13 || key.which==9){
				var date=$(this).text();
				var check=new checkDateFormat(date);
				if(check.enServer()){
					$(this).text(humanDate(date));
				}	
				event.stopImmediatePropagation();
			}
		})
		

		//configure author
		$('#pictureEditAuthor').live('focusout',function (){
			if($(this).text()!=='Insert author' && $(this).text()!=''){
				if($(this).text().indexOf('©')==-1){
					$(this).text('©'+$(this).text())
				}
			}					
		})
		
		//configure author on ENTER and TAB
		$('#pictureEditAuthor').keypress(function (key){
			if(key.which==13 || key.which==9){
				if($(this).text()!=='Insert author' && $(this).text()!=''){
					if($(this).text().indexOf('©')==-1){
						$(this).text('©'+$(this).text())
					}
				}
			}
		})


		
		
		$('#modalEditImage').click(function(){	
			var constX//=120*3;
			var constY//=90*3;
			
			constX=content.pictureInfo.width-20;
			constY=constX*90/120
			
			if(constY>content.pictureInfo.height){
				constY=content.pictureInfo.height-20;
				constX=constY*120/90;
			}
			
			var ix1=($(this).width()-constX)/2;
			var iy1=($(this).height()-constY)/2;
			var ix2=ix1+constX;
			var iy2=iy1+constY;
			
			thumbnailSelection={x:ix1, y:iy1, width:constX, height:constY};

			$(this).imgAreaSelect({ 
				aspectRatio: '12:9',
				handles: true, x1: ix1, y1: iy1, x2: ix2, y2: iy2,
				fadeSpeed:200,
				persistent: false,
				onSelectEnd: function (img,selection){
					thumbnailSelection={x:selection.x1, y:selection.y1, width:selection.width, height:selection.height};
				}
			});
		})

		$('#modalGallerySaveBtn').click(function(){
			if(!thumbnailSelection.width){
				alert('Click on the picture for thumbnail selection');
				return;
			}
			if(notEmptyInfo()){	
				if(content.pictureID){
					$.post('/scripts/imageEditor.php',{editPictureInfo:1,
						pictureID:content.pictureID,
						info:collectInfo()[0],
						pictureName:content.pictureName,
						newEvent:collectInfo()[1],
						eventList:collectInfo()[2],
						thumbnail:thumbnailSelection},
						function (response){
							if(response!==1){
								alert('Picture NOT saved. Reason: \n\n'+response)
							}else{
								$( "#modalWin" ).dialog('close');
							}
	
						},
						'json');

				}else{
					$.post('/scripts/imageEditor.php',{setPictureInfo:1,
						info:collectInfo()[0],
						pictureName:content.pictureName,
						newEvent:collectInfo()[1],
						eventList:collectInfo()[2],
						thumbnail:thumbnailSelection},
						function (response){
							if(isNaN(response)){
								alert('Picture NOT saved. Reason: \n\n'+response)
							}else{
								$( "#modalWin" ).dialog('close');
							}
						},
						'json');
				}
			}
		})
		$('#modalGalleryResetBtn').click(function(){
			$('.modalGalleryPictureDescription').text('Insert picture description');
			$('.modalGalleryPictureEventDate').text('Insert event date (year-month-day)');
			$('.modalGalleryPictureAuthor').text('Insert author');
			$('#ui-dialog-title-modalWin').text('Insert here event name or picture type: portraits, inprint, personal, artwork');					
		})
		
		function notEmptyInfo(){
			if($('#ui-dialog-title-modalWin').text()=='' || $('#ui-dialog-title-modalWin').text()=='Insert here event name or picture type: portraits, inprint, personal, artwork' || $('.modalGalleryPictureDescription').text()=='' || $('.modalGalleryPictureDescription').text()=='Insert picture description'){
				alert('Fill in the Event/Type and Description fields');
				return false;
			}else{
				return true
			}
		}
		
		function collectInfo(){
		var pictureType
		var event;
		var uiText=$('#ui-dialog-title-modalWin').text();
			if(uiText.toLowerCase()=='portraits' || uiText.toLowerCase()=='inprint' || uiText.toLowerCase()=='personal' || uiText.toLowerCase()=='artwork'){
				pictureType=uiText.toLowerCase();
				event='';
				newEvent=false;
			}else{
				pictureType='stage';
				event=$('#ui-dialog-title-modalWin').text();
				if(eventList.indexOf(event)==-1){
					newEvent=true;
				}else{
					newEvent=false;
				}
			}
			var author;
			var date;
			if($('#pictureEditAuthor').text()=='Insert author'){
				author='';
			}else{
				author=$('#pictureEditAuthor').html().slice(1);
			}
			if($('#pictureEditDate').text().length==4 && !isNaN($('#pictureEditDate').text())){
				date=$('#pictureEditDate').text()+'-00-00';
			}else{
				date=humanDate($('#pictureEditDate').text(),true);
			}
			var pictureInfo=[pictureType,event,$('#pictureEditDescription').html(),date,author,content.pictureInfo.width,content.pictureInfo.height];
			return new Array(pictureInfo,newEvent,eventList);
		}
	}
// ============ 
// ! add news   
// ============ 

	else if(type=='addNews'){
		if(content.id){
			$('#modalWin').html('<div id="newsEditorIconMenu"><div id="bold" class="newsEditorIcon justBold">B</div><div id="italic" class="newsEditorIcon justItalic">I</div><div id="underline" class="newsEditorIcon justUnderline">U</div><div id="createLink" class="newsEditorIcon justUnderline justBold">L</div><br><br><span id="upload" class="ui-icon ui-icon-check newsEditorIcon"></span><span id="reset" class="ui-icon ui-icon-close newsEditorIcon"></span></div><div id="newsEditorTitle" class="justDynamicColor" contenteditable="true">'+content.header+'</div><div id="newsEditorDate" contenteditable="true">'+humanDate(content.date)+'</div><div id="newsEditorField" contenteditable="true">'+content.message+'</div>');		
		}else{
			$('#modalWin').html('<div id="newsEditorIconMenu"><div id="bold" class="newsEditorIcon justBold">B</div><div id="italic" class="newsEditorIcon justItalic">I</div><div id="underline" class="newsEditorIcon justUnderline">U</div><div id="createLink" class="newsEditorIcon justUnderline justBold">L</div><br><br><span id="upload" class="ui-icon ui-icon-check newsEditorIcon"></span><span id="reset" class="ui-icon ui-icon-close newsEditorIcon"></span></div><div id="newsEditorTitle" class="justDynamicColor" contenteditable="true">Add title here</div><div id="newsEditorDate" contenteditable="true">Add date here (YYYY-MM-DD)</div><div id="newsEditorField" contenteditable="true">Add text here</div>');			
		}
			var link;
			var selection
			
			$('#newsEditorField').focusout(function (event){	
				selection=saveSelection();		
			})
			
			$('#upload').click(function(){
				upload();
			})
			
			$('#reset').click(function(){
				reset();
			})
			
			$('.newsEditorIcon').click(function(){
					if($(this).attr('id')!='createLink'){
						$('#newsEditorField').focus();
						restoreSelection(selection);
						document.execCommand($(this).attr('id'));
					}else{
						link=prompt('Insert link bellow (no http://)');
						$('#newsEditorField').focus();
						restoreSelection(selection);
						if(link){													
							document.execCommand('createLink',false,'http://'+link);
							link=null;
							$('a').attr('target','_blank').css('color',dynamicColor)
						}
					}
					
			})
			
			$('.newsEditorIcon').hover(
				function(){
					$(this).css('cursor','pointer');
					$(this).css('backgroundColor',dynamicColor);
				},
				function(){
					$(this).css('cursor','default');
					$(this).css('backgroundColor',siteColor.middleGrey);				
				}
			)
			
			$('#newsEditorDate').focusout(function(){
				var date=$(this).text();
				var check=new checkDateFormat(date);
				if(check.enServer()){
					$(this).text(humanDate(date));
				}	
				event.stopImmediatePropagation();			
			})
			
			function upload(){
				if(notEmptyInfoEditor()){
					if(!content.id){
						$.post('scripts/getNews.php',
								{insertNews:1,newsHeader:$('#newsEditorTitle').html(), newsDate:humanDate($('#newsEditorDate').text(),true), newsContent:$('#newsEditorField').html()},
								function (result){
									if(isNaN(result.news)){
										alert(result.news);
									}else{
										$( "#modalWin" ).dialog('close');
										seeLatest();
									}
						},'json');
					}else{
						$.post('scripts/getNews.php',
								{updateNews:1,newsHeader:$('#newsEditorTitle').html(), newsDate:humanDate($('#newsEditorDate').text(),true), newsContent:$('#newsEditorField').html(), id:content.id},
								function (result){
									if(isNaN(result.news)){
										alert(result.news);
									}else{
										$( "#modalWin" ).dialog('close');
										seeLatest();
									}							
								},'json');
					}					
				}
			}
			
			function reset(){
				$('#newsEditorTitle').text('Add title here');
				$('#newsEditorDate').text('Add date here (YYYY-MM-DD)');
				$('#newsEditorField').text('Add text here');
			}
			
			function notEmptyInfoEditor(){
				if($('#newsEditorTitle').text()=='' || $('newsEditorTitle').text()=='Add title here' || $('#newsEditorDate').text()=='' || $('#newsEditorDate').text()=='Add date here (YYYY-MM-DD)' || $('#newsEditorField').text()=='' || $('#newsEditorField').text()=='Add text here'){
					alert('Fill in the required fields');
					return false;
				}else{
					return true
				}
			}		
// =================
// ! add appearances   
// =================	
	}else if(type=="addAppearances"){
		if(content.id){
			$('#modalWin').html('<div id="newsEditorIconMenu"><span id="upload" class="ui-icon ui-icon-check newsEditorIcon"></span><span id="reset" class="ui-icon ui-icon-close newsEditorIcon"></span></div><span class="justBold justDynamicColor">name: </span> <div id="newsEditorTitle" class="newsEditorField" contenteditable="true">'+content.name+'</div><span class="justBold justDynamicColor">type: </span><div id="newsEditorType" class="newsEditorField" contenteditable="true">'+content.type+'</div><span class="justBold justDynamicColor">picture name: </span><div id="newsEditorPicture" class="newsEditorField" contenteditable="true">'+content.pictureName+'</div><span class="justBold justDynamicColor">dates: </span><div id="newsEditorDates" class="newsEditorField" contenteditable="true">'+content.dates+'</div><span class="justBold justDynamicColor">location:</span><div id="newsEditorLocation" class="newsEditorField" contenteditable="true">'+content.location+'</div><span class="justBold justDynamicColor">country: </span><div id="newsEditorCountry" class="newsEditorField" contenteditable="true">'+content.country+'</div><span class="justBold justDynamicColor">orchestra: </span><div id="newsEditorOrchestra" class="newsEditorField" contenteditable="true">'+content.orchestra+'</div><span class="justBold justDynamicColor">orchestra link: </span><div id="newsEditorOrchestraLink" class="newsEditorField" contenteditable="true">'+content.orchestraLink+'</div><span class="justBold justDynamicColor">venue: </span><div id="newsEditorVenue" class="newsEditorField" contenteditable="true">'+content.venue+'</div><span class="justBold justDynamicColor">venue link: </span><div id="newsEditorVenueLink" class="newsEditorField" contenteditable="true">'+content.venueLink+'</div><span class="justBold justDynamicColor">booking link: </span><div id="newsEditorBooking" class="newsEditorField" contenteditable="true">'+content.bookingLink+'</div><span class="justBold justDynamicColor">details link: </span><div id="newsEditorDetails" class="newsEditorField" contenteditable="true">'+content.detailsLink+'</div>');	
		}else{
			$('#modalWin').html('<div id="newsEditorIconMenu"><span id="upload" class="ui-icon ui-icon-check newsEditorIcon"></span><span id="reset" class="ui-icon ui-icon-close newsEditorIcon"></span></div><span class="justBold justDynamicColor">title: </span><div id="newsEditorTitle" class="justDynamicColor" contenteditable="true">Add event name here</div><span class="justBold justDynamicColor">type: </span><div id="newsEditorType" class="newsEditorField" contenteditable="true">Add event type here (opera, concert)</div><span class="justBold justDynamicColor">picture name: </span><div id="newsEditorPicture" class="newsEditorField" contenteditable="true">Add picture name here</div><span class="justBold justDynamicColor">dates: </span><div id="newsEditorDates" class="newsEditorField" contenteditable="true">Add dates here (YYYY-MM-DD) separated by a comma</div><span class="justBold justDynamicColor">location: </span><div id="newsEditorLocation" class="newsEditorField" contenteditable="true">Add location here (city)</div><span class="justBold justDynamicColor">country: </span><div id="newsEditorCountry" class="newsEditorField" contenteditable="true">Add country here</div><span class="justBold justDynamicColor">orchestra: </span><div id="newsEditorOrchestra" class="newsEditorField" contenteditable="true">Add orchestra here</div><span class="justBold justDynamicColor">orchestra link: </span><div id="newsEditorOrchestraLink" class="newsEditorField" contenteditable="true">Add orchestra link here</div><span class="justBold justDynamicColor">venue: </span><div id="newsEditorVenue" class="newsEditorField" contenteditable="true">Add venue here</div><span class="justBold justDynamicColor">venue link: </span><div id="newsEditorVenueLink" class="newsEditorField" contenteditable="true">Add venue link here</div><span class="justBold justDynamicColor">booking link: </span><div id="newsEditorBooking" class="newsEditorField" contenteditable="true">Add booking link here</div><span class="justBold justDynamicColor">details link: </span><div id="newsEditorDetails" class="newsEditorField" contenteditable="true">Add details link here</div>');			
		}	
			var oldDates=$('#newsEditorDates').text();
			var showName=$('#newsEditorTitle').text();
						
			$('#upload').click(function(){
				uploadAppearances();
			})
			
			$('#reset').click(function(){
				resetAppearances();
			})
						
			$('.newsEditorIcon').hover(
				function(){
					$(this).css('cursor','pointer');
					$(this).css('backgroundColor',dynamicColor);
				},
				function(){
					$(this).css('cursor','default');
					$(this).css('backgroundColor',siteColor.middleGrey);				
				}
			)
			
			function uploadAppearances(){
				if(notEmptyInfoEditorAppearances()){
						var val=[$('#newsEditorTitle').text(), $('#newsEditorType').text(), $('#newsEditorPicture').text(), $('#newsEditorVenue').text(), $('#newsEditorVenueLink').text(), $('#newsEditorLocation').text(), $('#newsEditorCountry').text(), $('#newsEditorOrchestra').text(), $('#newsEditorOrchestraLink').text(), $('#newsEditorDetails').text(), $('#newsEditorBooking').text()];
					if(!content.id){
						$.post('scripts/getAppearances.php',
								{insert:1,dates:$('#newsEditorDates').text(), values:val},
								function (result){
									if(isNaN(result.info)){
										alert(result.info);
									}else if(result.info>0){
										$( "#modalWin" ).dialog('close');
										seeAll();
									}
						},'json');
					}else{
						$.post('scripts/getAppearances.php',
								{update:1,oldDates:oldDates , newDates:$('#newsEditorDates').text(), showName:showName , info:val},
								function (result){
									if(isNaN(result.info)){
										alert(result.info);
									}else if(result.info>0){
										$( "#modalWin" ).dialog('close');
										seeAll();
									}
						},'json');
					}					
				}
			}
			
			function resetAppearances(){
				$('#newsEditorTitle').text('Add event name here');
				$('#newsEditorDates').text('Add dates here (YYYY-MM-DD) separated by a comma');
				$('#newsEditorLocation').text('Add location here');
				$('#newsEditorVenue').text('Add venue here');
				$('#newsEditorBooking').text('Add booking link here');
				$('#newsEditorDetails').text('Add details link here');
			}
			
			function notEmptyInfoEditorAppearances(){
				if($('#newsEditorTitle').text()=='' || $('newsEditorTitle').text()=='Add event name here' || $('#newsEditorDates').text()=='' || $('#newsEditorDates').text()=='Add dates here (YYYY-MM-DD) separated by a comma' || $('#newsEditorLocation').text()=='' || $('#newsEditorLocation').text()=='Add location here (city)' || $('#newsEditorBooking').text()=='' || $('#newsEditorBooking').text()=='Add booking link here' || $('#newsEditorDetails').text()=='' || $('#newsEditorDetails').text()=='Add details link here' || $('#newsEditorVenue').text()=='' || $('#newsEditorVenue').text()=='Add venue here'){
					alert('Fill in the required fields');
					return false;
				}else{
					return true
				}
			}			

// =================
// ! add press   
// =================
	}else if(type=='addPress'){
		if(content.id){
			$('#modalWin').html('<div id="newsEditorIconMenu"><div id="bold" class="newsEditorIcon justBold">B</div><div id="italic" class="newsEditorIcon justItalic">I</div><div id="underline" class="newsEditorIcon justUnderline">U</div><div id="createLink" class="newsEditorIcon justUnderline justBold">L</div><br><br><span id="upload" class="ui-icon ui-icon-check newsEditorIcon"></span><span id="reset" class="ui-icon ui-icon-close newsEditorIcon"></span></div><div id="newsEditorTitle" class="newsEditorField" class="justDynamicColor" contenteditable="true">'+content.title+'</div><div id="newsEditorDate" class="newsEditorField" contenteditable="true">'+content.date+'</div><div id="newsEditorAuthor" class="newsEditorField" contenteditable="true">'+content.author+'</div><div id="newsEditorType" class="newsEditorField" contenteditable="true">'+content.type+'</div><div id="newsEditorPicture" class="newsEditorField" contenteditable="true">'+content.picture+'</div><div id="newsEditorShortDescription" class="newsEditorField" contenteditable="true">'+content.shortDescription+'</div><div id="newsEditorField" class="newsEditorField" contenteditable="true">'+content.readMore+'</div>');		
		}else{
			$('#modalWin').html('<div id="newsEditorIconMenu"><div id="bold" class="newsEditorIcon justBold">B</div><div id="italic" class="newsEditorIcon justItalic">I</div><div id="underline" class="newsEditorIcon justUnderline">U</div><div id="createLink" class="newsEditorIcon justUnderline justBold">L</div><br><br><span id="upload" class="ui-icon ui-icon-check newsEditorIcon"></span><span id="reset" class="ui-icon ui-icon-close newsEditorIcon"></span></div><div id="newsEditorTitle" class="newsEditorField" class="justDynamicColor" contenteditable="true">Add title here</div><div id="newsEditorDate" class="newsEditorField" contenteditable="true">Add date here (YYYY-MM-DD)</div><div id="newsEditorAuthor" class="newsEditorField" contenteditable="true">Add author and publication here</div><div id="newsEditorType" class="newsEditorField" contenteditable="true">Add type here (review, interview, release)</div><div id="newsEditorPicture" class="newsEditorField" contenteditable="true">Add picture name here</div><div id="newsEditorShortDescription" class="newsEditorField" contenteditable="true">Add short description here</div><div id="newsEditorField" class="newsEditorField" contenteditable="true">Add text here</div>');			
		}
			var link;
			var selection
			
			$('#newsEditorField').focusout(function (event){	
				selection=saveSelection();		
			})
			
			$('#upload').click(function(){
				uploadPress();
			})
			
			$('#reset').click(function(){
				resetPress();
			})
			
			$('.newsEditorIcon').click(function(){
					if($(this).attr('id')!='createLink'){
						$('#newsEditorField').focus();
						restoreSelection(selection);
						document.execCommand($(this).attr('id'));
					}else{
						link=prompt('Insert link bellow (no http://)');
						$('#newsEditorField').focus();
						restoreSelection(selection);
						if(link){													
							document.execCommand('createLink',false,'http://'+link);
							link=null;
							$('a').attr('target','_blank').css('color',dynamicColor)
						}
					}
					
			})
			
			$('.newsEditorIcon').hover(
				function(){
					$(this).css('cursor','pointer');
					$(this).css('backgroundColor',dynamicColor);
				},
				function(){
					$(this).css('cursor','default');
					$(this).css('backgroundColor',siteColor.middleGrey);				
				}
			)
			
			$('#newsEditorDate').focusout(function(){
				var date=$(this).text();
				var check=new checkDateFormat(date);
				if(check.enServer()){
					$(this).text(humanDate(date));
				}	
				event.stopImmediatePropagation();			
			})
			
			function uploadPress(){
				if(notEmptyInfoEditorPress()){
					var pressInfo=new Array($('#newsEditorType').html(), $('#newsEditorTitle').html(), $('#newsEditorAuthor').html(), $('#newsEditorShortDescription').html(), $('#newsEditorField').html(), $('#newsEditorPicture').html(), humanDate($('#newsEditorDate').html(),1))
					if(!content.id){
						$.post('scripts/getPress.php',
								{insert:1,pressInfo:pressInfo},
								function (result){
									if(isNaN(result.articles) || result.articles==0){
										alert(result.articles);
									}else{
										$( "#modalWin" ).dialog('close');
									}
						},'json');
					}else{
						$.post('scripts/getPress.php',
								{update:1,updateInfo:pressInfo, id:content.id},
								function (result){
									if(isNaN(result.articles) || result.articles==0){
										alert(result.articles);
									}else{
										$( "#modalWin" ).dialog('close');
									}							
								},'json');
					}					
				}
			}
			
			function resetPress(){
				$('#newsEditorTitle').text('Add title here');
				$('#newsEditorDate').text('Add date here (YYYY-MM-DD)');
				$('#newsEditorField').text('Add text here');
			}
			
			function notEmptyInfoEditorPress(){
				if($('#newsEditorTitle').text()=='' || $('newsEditorTitle').text()=='Add title here' || $('#newsEditorDate').text()=='' || $('#newsEditorDate').text()=='Add date here (YYYY-MM-DD)' || $('#newsEditorField').text()=='' || $('#newsEditorField').text()=='Add text here'){
					alert('Fill in the required fields');
					return false;
				}else{
					return true
				}
			}		
// =================
// ! add mediaplayer   
// =================	
	}else if(type=="mediaplayer"){

	var pages=new goto(content.playList,5)
	function gotoPlayer(direction){
		var currentPlaylist;
			if(direction=='next'){
				currentPlaylist=pages.next()
			}else if(direction=='previous'){
				currentPlaylist=pages.previous()
			}
/* 			$('#modalWin').html('<div id="mediaPlayerNavigation"><span id="mpPrevious" class="ui-icon ui-icon-triangle-1-w mparrow"></span><span id="mpNext" class="ui-icon ui-icon-triangle-1-e mparrow"></span></div><div id="mediaPlayerTrackList"></div>'); */
			for(i=0;i<currentPlaylist.length;i++){
				$('#modalWin').append('<div class="mediaPlayerTrack" id="mptrack_'+currentPlaylist[i].id+'" time="'+currentPlaylist[i].time+'"><span class="justBold justDynamicColor trackName">'+currentPlaylist[i].trackName+'</span> <span class="mpTime">('+currentPlaylist[i].time+')</span><br>album: <span class="justBold albumName">'+currentPlaylist[i].albumName+'</span><br>composer: <span class="justBold composer">'+currentPlaylist[i].composer+'</span><span class="ui-icon ui-icon-volume-off mpStatusIcon"></span></div>');
			}
/* 			$('#modalWin').append('<div id="mediaPlayerNavigation"><span id="mpPrevious" class="ui-icon ui-icon-triangle-1-w mparrow"></span><span id="mpNext" class="ui-icon ui-icon-triangle-1-e mparrow"></span></div>'); */
			
			//top margin for first
			$('.mediaPlayerTrack:first').css('margin-top','20px');
			//line bellow last track
			$('.mediaPlayerTrack:last').css('border-bottom-color','#9298aa').css('border-bottom-width','1px').css('border-bottom-style','solid').css('height','40px').css('margin-bottom','10px');
			
			//hover and clicks
			$('.mediaPlayerTrack').hover(
				function(){
					$(this).css('cursor','pointer');
					$(this).css('background-color',siteColor.middleGrey);
				},
				function(){
					$(this).css('cursor','default');
					$(this).css('background-color','transparent');
				}
			)
			
			$('.mediaPlayerTrack').click(function(){				
				var id=$(this).attr('id').split('_')[1];
				//stop from playlist
				if(currentMediaPlaying.currentID){
					mediaPlayerStop();
					$('.mpStatusIcon','#mptrack_'+lastPlayedID).removeClass('ui-icon-volume-on');
					$('.mpStatusIcon','#mptrack_'+lastPlayedID).addClass('ui-icon-volume-off');
					$('.trackName','#mptrack_'+lastPlayedID).css('color',dynamicColor);
					$('.mpTime','#mptrack_'+lastPlayedID).text(' ('+$('#mptrack_'+lastPlayedID).attr('time')+')');
					//if is not the same item go on and play
					if(lastPlayedID==id){
						return;
					}
					
				}
				if(browserCap.hasAudio){
					$('.mpStatusIcon',this).removeClass('ui-icon-volume-off');
					$('.mpStatusIcon',this).addClass('ui-icon-transferthick-e-w');	
					$('.mpTime',this).text(' (--)');					
					mediaPlayer('play',function(status,message){
						if(status=='playing'){
							$('.mpStatusIcon','#mptrack_'+id).removeClass('ui-icon-transferthick-e-w');
							$('.mpStatusIcon','#mptrack_'+id).addClass('ui-icon-volume-on');
							$('.trackName','#mptrack_'+currentMediaPlaying.currentID).css('color',siteColor.lightGrey);
							mediaPlayerCounter($('.mpTime','#mptrack_'+id));
/*
							currentMediaPlaying.trackName=$('.trackName','#mptrack_'+currentMediaPlaying.currentID).text();
							currentMediaPlaying.composer=$('.composer','#mptrack_'+currentMediaPlaying.currentID).text();
							currentMediaPlaying.albumName=$('.albumName','#mptrack_'+currentMediaPlaying.currentID).text();
*/
						}else if(status=='stopped'){
							$('.mpStatusIcon','#mptrack_'+lastPlayedID).removeClass('ui-icon-volume-on');
							$('.mpStatusIcon','#mptrack_'+lastPlayedID).addClass('ui-icon-volume-off');
							$('.trackName','#mptrack_'+lastPlayedID).css('color',dynamicColor);
							$('.mpTime','#mptrack_'+lastPlayedID).text(' ('+$('#mptrack_'+lastPlayedID).attr('time')+')');
						}else if(status=='error'){
								$('.mpStatusIcon','#mptrack_'+id).removeClass('ui-icon-transferthick-e-w');
								$('.mpStatusIcon','#mptrack_'+id).addClass('ui-icon-notice');
								alert(message);
						}
					},id,'/tracks/'+id+browserCap.audioExtension,'audio');				
				}else{
					alert('Your browser cannot play audio files.\nPlease update it to a HTML5 compliant version.');
				}								
			})
			
			//set active media playing attributes in player
			if(mediaPlaying()){
				$('.mpStatusIcon','#mptrack_'+currentMediaPlaying.currentID).removeClass('ui-icon-volume-off');
				$('.mpStatusIcon','#mptrack_'+currentMediaPlaying.currentID).addClass('ui-icon-volume-on');
				$('.trackName','#mptrack_'+currentMediaPlaying.currentID).css('color',siteColor.lightGrey);
				mediaPlayerCounter($('.mpTime','#mptrack_'+currentMediaPlaying.currentID));
			}
		}
		
		gotoPlayer('next');

	}
// ========== 
// ! footer   
// ========== 	
	else if(type=='links'){
		$( "#modalWin" ).html('<div class="footerLinkContainer"><img src="images/logoEMI.jpeg" width="59px" height="59px" alt="EMI" class="justFloatLeft footerLinksImage"/><h3>EMI Classics</h3><a href="http://www.emiclassics.com">http://www.emiclassics.com</a></div><div class="footerLinkContainer"><img src="images/logoDECCA.jpeg" width="59px" height="59px" alt="EMI" class="justFloatLeft footerLinksImage"/><h3>Decca Music Group</h3><a href="http://www.deccaclassics.com">http://www.deccaclassics.com</a></div><div class="footerLinkContainer"><img src="images/logoROH.jpeg" width="59px" height="59px" alt="EMI" class="justFloatLeft footerLinksImage"/><h3>Royal Opera House</h3><a href="http://www.royaloperahouse.org">http://www.royaloperahouse.org</a></div><div class="footerLinkContainer"><img src="images/logoMET.jpeg" width="59px" height="59px" alt="EMI" class="justFloatLeft footerLinksImage"/><h3>The Metropolitan Opera</h3><a href="http://www.metoperafamily.org/metopera">http://www.metoperafamily.org/metopera</a></div><div class="footerLinkContainer"><img src="images/logoSFO.jpeg" width="59px" height="59px" alt="EMI" class="justFloatLeft footerLinksImage"/><h3>San Francisco Opera</h3><a href="http://www.sfopera.com">http://www.sfopera.com</a></div>');
	}else if(type=='rights'){
		$( "#modalWin" ).html('<p>Please note that all material included on this site is either our copyright or as specified and may only be downloaded for your personal use. Any further distribution for sale or otherwise or use in any other manner is expressly prohibited. You are also prohibited from publicly performing or broadcasting any of the recordings included on this site without our express written consent.</p><p class="justBold">2008 - Copyright angelagheorghiu.com</p>');
	}else if(type=='privacy'){
		$( "#modalWin" ).html('<div class="justJustify"><p><span class="justBold">angelagheorghiu.com</span> may from time to time collect names and/or details of website visitors. This may include the mailing list, blog comments sections and in various sections of the <span class="justBold">angelagheorghiu.com</span> site. We will never send you information unless you have given us permission to do so by subscribing to the mailing list.</p><p>These details will not be passed onto any other third party or other organisation unless we are required to by government or other law enforcement authority.</p><p>If you contribute content, including but not limited to forum and guestbook posts on this site, this content may be publicly displayed including personally identifiable information.</p><p>Unsubscribe at <span class="justBold">angelagheorghiu.com</span></p><p><span class="justBold">angelagheorghiu.com</span> links to independently run web sites outside of the <span class="justBold">angelagheorghiu.com</span> domain. <span class="justBold">angelagheorghiu.com</span> does not take any responsibility for the content on these sites, nor their privacy policies.</p><p><span class="justBold">angelagheorghiu.com</span> may use cookies to save login details and to collect statistical information about the numbers of visitors to the site.</p><p><span class="justBold">angelagheorghiu.com</span> is suitable for all ages.</p><p>Should we change this privacy policy, these changes will be posted on this page</p></div>');
	}
	
	//get position
/*
	var mX=(docWidth-modalWidth)/2;
	var mY=0;
*/

	//set up modal
	$( "#modalWin" ).dialog({
			height: modalHeight,
			width: modalWidth,
			autoOpen: false,
			hide: 'explode',
			modal: true,
			title: content.title,
			resizable:false,
		});
	
	//scroll top if modal is bigger than window
	if($( "#modalWin" ).dialog('widget').height()>=$(window).height()){
		window.scroll(0,0);
	}

		
	if(!$( "#modalWin" ).dialog('isOpen')){
		$( "#modalWin" ).dialog('open');
	}
	
	if(type=='pictureGallery'){
		$('#modalWin').dialog('option', 'dialogClass','justTransparentBack');
		$('.ui-dialog-titlebar').addClass('justTransparentBack')
		$('.ui-dialog-titlebar').html('')
		$('#ui-dialog-title-modalWin').text('')
	}
	
	//modal icon hover
	$('.modalIcon').hover(
		function(){
			$(this).css('cursor','pointer');
			$(this).css('backgroundColor',dynamicColor)
		},
		function(){
			$(this).css('cursor','default');
			$(this).css('backgroundColor',siteColor.middleGrey);
		}				
	)

	//add autocomplete field for title bar
	if(type=='editPicture'){
	
		//get events for autocomplete
		$.post('/scripts/imageEditor.php',{getGalleryEvents:1},function (response){
			eventList=response;
		},'json')
		
		//eventList=['one','two','three']
		
		$("#ui-dialog-title-modalWin").click(function (){
					var initValue=$('#ui-dialog-title-modalWin').text();
					if(initValue!=='Insert here event name or picture type: portraits, inprint, personal, artwork'){
						initValue=$('#ui-dialog-title-modalWin').text();
					}else{
						initValue='';
					}
					$('#ui-dialog-title-modalWin').html('<input size="100" id="tags" value="'+initValue+'">');
					if(eventList){
						$('#tags').autocomplete({
							source:eventList,
							delay:100,
							minLength:0,
							autoFocus:false,
							change:function (){							
								changeValue($('#tags').val());
							},
							select:function (){							
								changeValue($('#tags').val())
							},
							focus:function (event, ui){
								$('#tags').val(ui.item.value)
							}
						})
					}
					$('#tags').autocomplete( 'search','' );
					//get focus on input field on click
					$('#tags').focus();
					//don't erase the value inside
					$('#tags').select(function (){
						$(this).val($(this).val());
					});
					//set on ENTER and TAB
					$('#tags').keydown(function (key){
						if(key.which==13 || key.which==9){
							changeValue($('#tags').val());
						}
					})
					
					function changeValue(value){
						if(value!==''){
							$('#ui-dialog-title-modalWin').text(value);
						}else{
							$('#ui-dialog-title-modalWin').text(content.title);
						}
						$('.modalGalleryPictureDescription').focus();
					}					
		})
		
	}
	
	//remove a from empty href elements	
	$( "#modalWin a").each(function(){
		if($(this).attr('href')==''){
			if($(this).parent().hasClass('modalAlbumButton')){
				$(this).parent().remove();
			}else{
				$(this).replaceWith('TBD')
			}
		}
	})
	//settings for albums
	if(type=='album'){
		//center modalAlbumButtons
		var enclosureWidth=0;
		$( "#modalWin .modalAlbumButton").each(function(){
			enclosureWidth+=$(this).outerWidth(true);
		})
		$('.modalAlbumButtonsEnclosure').width(enclosureWidth);
		//remove buy option
		if($('.modalAlbumButton').length<=0){
			$('.modalAlbumBuyButtons').remove();
			$('.modalAlbumTrackContainer').css('top','10px');
			$( '.modalAlbumContainer').height('300');
		}
		
	}	
	//remove focus on link
	$('.ui-dialog :link').blur();
	
	//add dynamic color color to links	
	$('a').hover(
		function(){
			$(this).css('color',dynamicColor)
		},
		function(){
			$(this).css('color','white	')
		}
	)
	
	//glowing button behavior
	$('.modalButton').hover(
		function(){
			buttonBehavior(this,'buttonMouseOver','hover');
			glowingBackground(this,'#33323a');
		},
		function(){
			buttonBehavior(this,'buttonMouseOver','leave');
			glowingBackground(this,'#9298aa');
		}
	)
	
	//make title dynamic
	$(".ui-dialog-titlebar").addClass('justDynamicColor');
	
	
	$('.ui-dialog :link').click(function(){
		$( "#modalWin" ).dialog('close');
	});
	
	//modal discography player functions
	
	$('.modalAlbumTrack').hover(
		function(){
			var id=$(this).attr('id');
			$('#trackName_'+id).css('cursor','pointer');
			$(('#trackName_'+id)).addClass('justDynamicColor');
			//$('#track_'+$(this).attr('id')).css('background-color',dynamicColor);
		},
		function(){
			var id=$(this).attr('id');
			$('#trackName_'+id).removeClass('justDynamicColor');
			//$('#track_'+$(this).attr('id')).css('background-color','transparent');
		}
	)
	
	$('.modalAlbumTrack').click(function(){
	
			var id=$(this).attr('id');
			if(browserCap.hasAudio){
				$('#track_'+id).removeClass('ui-icon-volume-off');
				$('#track_'+id).addClass('ui-icon-transferthick-e-w');	
				$('#time_'+id).text(' (--)');					
				mediaPlayer('play',function(status){
					if(status=='playing'){
						$('#track_'+id).removeClass('ui-icon-transferthick-e-w');
						$('#track_'+id).addClass('ui-icon-volume-on');
						$('#trackName_'+id).css('color',siteColor['lightGrey']);						
						mediaPlayerCounter($('#time_'+id),30);
					}else if(status=='stopped'){
						$('#track_'+lastPlayedID).removeClass('ui-icon-volume-on');
						$('#track_'+lastPlayedID).addClass('ui-icon-volume-off');
						$('#trackName_'+lastPlayedID).css('color',siteColor['white']);
					}
				},id,'/tracks/'+$(this).attr('id')+browserCap.audioExtension,'audio');
			}else{
				alert('Your browser cannot play audio files.\nPlease update it to an HTML5 compliant version.')
			}
			//

	})
		
	//guestbook submit button
	$('.modalGuestBookSubmitButton').click(function(){
		if(checkEmptyField($('#guestbookMessage'))){
			alert('Please fill in the message field.')
		}else{
			//with login
			//$.post("scripts/getGuestbook.php",{uploadMessage:{userID:userInfo.id,message:$('#guestbookMessage').val()}},function(result){
			//without login
			$.post("scripts/getGuestbook.php",{uploadMessage:{name:$('#guestbookName').val(), email:$('#guestbookEmail').val(), country:$('#guestbookCountry').val(), message:$('#guestbookMessage').val()}},function(result){
				
				if(result){
					$( "#modalWin" ).dialog('close');
				}else{
					alert('Your message could not be sent due to a server error. Please try again later.')
				}
					
			},'json');
		}
		
	})
	
	//reset player before close

	$( "#modalWin" ).dialog({beforeClose:function(){
		if(mediaPlaying() && type=='album'){
			mediaPlayer('stop')
		}
		if(type=='editPicture'){
			$('#modalEditImage').imgAreaSelect({remove:true});
		}
		
		if(type='pictureGallery'){
			$('.pictureSliderIcon').die();
		}
		
	}});

	// destroy on close
	$( "#modalWin" ).dialog({close:function(){
		$( "#modalWin" ).dialog('destroy');
		if(BubbleObject){
			BubbleObject.UnfreezeAllBubblePopups();
		}
	}});
	
}


// ====================== 
// ! unique array items   
// ====================== 

function uniqueArray(arr) {
    var a = [], l = arr.length;
    for(var i=0; i<l; i++) {
        for(var j=i+1; j<l; j++)
            if (arr[i] === arr[j]) j = ++i;
        a.push(arr[i]);
    }
    return a;
};

function seeObject(testObj){
	var textObj=new Array();
	for (key in testObj){
		textObj.push(key +" : "+testObj[key]);     
	}
	return textObj.join('\n');
}

// ==================== 
// ! form validations   
// ==================== 

function isValidEmailAddress(email){
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(email);
}

function checkEmptyField(field){
	if(!$(field).val()){
		return $(field).attr('name') ;
	}else{
		return false;
	}

}

function valueMatch(value1,value2){
	if(value1!==value2){	
		return false;
	}else{
		return true;
	}
}

function userRegistered(){
	if($('#login').text()=='log out'){		
		return true;	
	}else{
		return false;
	}
}

function checkLoginUser(){
	var info;
	if(Modernizr.localstorage){
		if(localStorage['userInfo']){
			if(localStorage['persistent']){
				info=JSON.parse(localStorage['userInfo']);
				setupUserInterface(info);			
			}else{
				localStorage.removeItem('userInfo');
			}
		}else{
			$('#login').text('log in');		
		}
	}else{
		$.post("scripts/getSession.php",{getUserInfo:1},function(answer){
			if(answer.result){
				setupUserInterface(answer.result)
			}else{
				$('#login').text('log in');
			}
		},'json');	
	}

}

function setupUserInterface(info){
		userInfo=info;
		$('#login').text('log out');		
		$('#rightTopMenu').append('<div id="userInfo">Welcome back, '+userInfo.firstName+' '+userInfo.lastName+'</div>');
		//set admin mode
		if(userInfo.type=='admin'){
			adminMode();
			editable=true;
		}else{
			editable=false;
		}
}

function disableUserInterface(){
	$('#login').text('log in');
	$('#userInfo').remove();
}

function logoutUser(){
	if(Modernizr.localstorage){
		localStorage.removeItem('userInfo');
		localStorage.removeItem('persistent');
		disableUserInterface();
	}else{
		$.post("scripts/getUserData.php",{logout:1},function(){
			disableUserInterface()
		},'json');
	}
	window.location.reload();
}

function setGlobals(){
	//check local storage availability
	if(Modernizr.localstorage){	
		//detect browser capabilities
		if(!localStorage.browserCap){
			if(Modernizr.audio){
				browserCap.hasAudio=true;
			}else{
				browserCap.hasAudio=false;
			}
			
			if(Modernizr.video){
				browserCap.hasVideo=true;
			}else{
				browserCap=false;
			}
			
			if(Modernizr.audio.mp3){
				browserCap.audioExtension='.mp3';
			}else if(Modernizr.audio.ogg){
				browserCap.audioExtension='.ogg';
			}else{
				browserCap.audioExtension=false;
			}
		
			
			if(Modernizr.video.webm){
				browserCap.videoExtension='.webm';
			}else if(Modernizr.video.ogg){
				browserCap.videoExtension='.ogg';
			}else if(Modernizr.video.h264){
				browserCap.videoExtension='.mp4';
			}else{
				browserCap.videoExtension=false;
			}

			localStorage['browserCap']=JSON.stringify(browserCap);			
		}else{
			browserCap=JSON.parse(localStorage['browserCap']);
		}
	}
	//save globals in session
	else{
		//alert('No localstorage')
	}
	//window width and height
	browser.width=$(window).width();
	browser.height=$(window).height();
}

//localStorage.clear()

//page by page navigation global function

function gotoPage(page){
	//reset current page
	var currentPage=new Array();
	//length <= limit => one page, no navigation
	if(gotoContent.length<=gotoLimit){
		//gotoNext=false;
		gotoPrevious=false;
		return gotoContent;
	}
	//detect last page items and the number of pages
	if((gotoContent.length/gotoLimit)-Math.floor(gotoContent.length/gotoLimit)==0){
		gotoLastPageNo=Math.floor(gotoContent.length/gotoLimit);
	}else{
		gotoLastPageNo=Math.floor(gotoContent.length/gotoLimit)+1;
	}
	
	//enable/disable arrows/direction according with the current page number	
	function setArrows(){
		if(gotoCurrentPageNo<gotoLastPageNo){
			//go next up to last page
			gotoNext=true;
		}else{
			//stop going next on the last page
			gotoNext=false;
		}
		if(gotoCurrentPageNo>1){
			//go prev up to first page
			gotoPrevious=true;
		}else{
			//stop going prev on first page
			gotoPrevious=false;
		}
	}
	
	function getCurrentPage(){
			for(i=0;i<gotoLimit;i++){
				if(gotoContent[gotoBookmark]!=null){
					//push element in the current page only if it exist in the original array
					currentPage.push(gotoContent[gotoBookmark]);
				}
				//update bookmark anyway in order to have consistent page numbering (bookmark will be always divided by page limit)
				gotoBookmark++;
			}
	}
	//go next			
	if(page=='next' || page=='+'){
		if(gotoNext){
			getCurrentPage()
			//update current page number	
			gotoCurrentPageNo++;
			//update possible direction - arrows
			setArrows()
			//return the result - current page items
			return currentPage;
		}else{
			return false;
		}
	//go previous		
	}else if(page=='prev' || page=='previous' || page=='-'){
		if(gotoPrevious){
			//substract 2 pages of items from the bookmark and then... go next page
			gotoBookmark=gotoBookmark-2*gotoLimit;			
			getCurrentPage()
			gotoCurrentPageNo--;
			setArrows()
			return currentPage;
		}else{
			return false;
		}		
	}else if(page=='reset'){
		 gotoContent=new Array();
		 gotoBookmark=0;
		 gotoLimit=0;
		 gotoLastPageNo;
		 gotoCurrentPageNo=0;
		 gotoNext=true;
		 gotoPrevious=false;
	}
}

//page by page navigation class

function goto(content,limit){

	this.currentPage=new Array();
	this.gotoContent=content;
	this.gotoBookmark=0;	
	this.gotoLimit=limit;
	this.gotoLastPageNo;
	this.gotoCurrentPageNo=0;
	this.gotoNext=true;
	this.gotoPrevious=false;
	
	//detect last page items and the number of pages
	if((this.gotoContent.length/this.gotoLimit)-Math.floor(this.gotoContent.length/this.gotoLimit)==0){
		this.gotoLastPageNo=Math.floor(this.gotoContent.length/this.gotoLimit);
	}else{
		this.gotoLastPageNo=Math.floor(this.gotoContent.length/this.gotoLimit)+1;
	}
	
	//enable/disable arrows/direction according with the current page number	
	this.setArrows=function (){
		if(this.gotoCurrentPageNo<this.gotoLastPageNo){
			//go next up to last page
			this.gotoNext=true;
		}else{
			//stop going next on the last page
			this.gotoNext=false;
		}
		if(this.gotoCurrentPageNo>1){
			//go prev up to first page
			this.gotoPrevious=true;
		}else{
			//stop going prev on first page
			this.gotoPrevious=false;
		}
	}
	
	this.getCurrentPage=function (){
			for(i=0;i<this.gotoLimit;i++){
				if(this.gotoContent[this.gotoBookmark]!=null){
					//push element in the current page only if it exist in the original array
					this.currentPage.push(this.gotoContent[this.gotoBookmark]);
				}
				//update bookmark anyway in order to have consistent page numbering (bookmark will be always divided by page limit)
				this.gotoBookmark++;
			}
	}
	
	this.checkLimit=function(){
		if(this.gotoContent.length>this.gotoLimit){
			return true;
		}else{
			return false;
		}
	}

	this.next=function(){
		//reset curent page
		this.currentPage=new Array();
		if(this.checkLimit()){
			if(this.gotoNext){
				this.getCurrentPage()
				//update current page number	
				this.gotoCurrentPageNo++;
				//update possible direction - arrows
				this.setArrows()
				//return the result - current page items
				return this.currentPage;
			}else{
				return false;
			}
		}else{
			this.currentPage=this.gotoContent;
			this.gotoLastPageNo=1;
			this.gotoCurrentPageNo=1;
			this.gotoNext=false;
			this.gotoPrevious=false;
			return this.currentPage
		}
	}
	
	this.previous=function(){		
			if(this.gotoPrevious){
				this.currentPage=new Array();
				//substract 2 pages of items from the bookmark and then... go next page
				this.gotoBookmark=this.gotoBookmark-2*this.gotoLimit;			
				this.getCurrentPage()
				this.gotoCurrentPageNo--;
				this.setArrows()
				return this.currentPage;
			}else{
				return false;
			}
	}
	
	this.jumpToPage=function(page){
		this.currentPage=new Array();
		if(page==this.gotoCurrentPageNo || page>this.gotoLastPageNo || page<1){
			return false
		}else{
			this.gotoBookmark=page*this.gotoLimit-this.gotoLimit;
		}		
		this.getCurrentPage()
		this.gotoCurrentPageNo=page;
		this.setArrows()
		return this.currentPage;
	}
		
	this.reset=function(){
		this.gotoContent=new Array();
		this. gotoBookmark=0;
		this. gotoLimit=0;
		this. gotoLastPageNo;
		this. gotoCurrentPageNo=0;
		this. gotoNext=true;
		this. gotoPrevious=false;
	}
}


function imagePreloader(imagesArray,path){
	this.images=imagesArray;
	if(path){
		this.path=path;
	}

	this.preload=function () {
	    $(this.images).each(function(){
		    if(this.path){
		    	$('<img/>')[0].src = this.path+'/'+this;
		    }else{
		    	$('<img/>')[0].src = this;
		    }	        
	    });
	}
	
	this.preload()
}

function adminMode(){
	var adminMenu=$('#rightTopMenu > #userInfo');
	var nothingToAdd=['biography.html','discography.html','guestbook.html'];
	var editPages=['gallery.html','news.html','press.html','appearances.html','index.html'];
	if(adminMenu.length>0 && nothingToAdd.indexOf(currentPage)==-1){
		adminMenu.append('<span id="topAdminAdd" class="ui-icon ui-icon-circle-plus ui-mask-black"></span>');
		//add hiden file button for gallery
		if(currentPage=='gallery.html'){
				var formOptions={action:'/scripts/imageEditor.php',method:'post',id:'fileUploader',enctype:"multipart/form-data",id:"upGalleryForm"};
				var fileOptions={accept:"image/gif,image/jpeg",multiple:'',name:'upGallery'};
				var inputButton=$('#rightTopMenu > #userInfo > #topAdminAdd');
				//create custom button
				inputButton.file(formOptions,fileOptions,false);
				var submitOptions = {success:pictureUpload,dataType:'json' };
				//
				$(inputButton+':input').change(function(){
					//loading message
					loadingMessage('block','Picture loading…');
					//$('#rightTopMenu > #userInfo > #topAdminAdd').trigger('mouseout');
					$('#upGalleryForm').ajaxSubmit(submitOptions);
				})		
		}else if(currentPage=='index.html' || currentPage=='' ){
				$('#topAdminAdd').wrap('<a href="../emailer/template.html">');
		}else{
			//do something on click
			$('#rightTopMenu > #userInfo > #topAdminAdd').click(function(){
				if(editPages.indexOf(currentPage)!=-1){
					adminAddItems();
				}
			})		
		}
		
		//hover behavior
		$('#rightTopMenu > #userInfo > #topAdminAdd').hover(
			function(event){
				$(this).css('cursor','pointer');
				$(this).css('backgroundColor',dynamicColor);
				
			},function(){
				$(this).css('cursor','default');
				$(this).css('backgroundColor','transparent');
			}
		)
	}
}

function adminAddItems(){
	if(currentPage=='gallery.html'){
		pictureAdd();
	}else if(currentPage=='press.html'){
		//generatePDFs();
		addPress();
	}else if(currentPage=='news.html'){
		addNews();
	}else if(currentPage=='appearances.html'){
		addAppearances();
	}
}

function addPress(){
	var content={title:"Press Editor"};
	createPopUpWindow('addPress',content, 650, 750);
}

function addAppearances(){
	var content={title:"Appearances Editor"};
	createPopUpWindow('addAppearances',content, 650, 550);
}

function addNews(){
	var content={title:"News Editor"};
	createPopUpWindow('addNews',content, 650, 400);
}

function generatePDFs(){
	loadingMessage('block','Generating PDF\'s…');
	$.post("scripts/getPress.php",{pdf:1},function (result){
		loadingMessage('unblock');
		alert(result.articles+' PDF\'s were generated.');	
	},'json');
}

function pictureUpload(response){
	if(response.result){
		if(response.type=='gallery'){
			//open modal window for editing
			var content={title:'Insert here event name or picture type: portraits, inprint, personal, artwork', pictureName:response.pictureName,pictureInfo:response.pictureInfo};
			content.pictureInfo.description='Insert picture description';
			content.pictureInfo.author='Insert author';
			content.pictureInfo.date='Insert event date (year-month-day)';
			//
			loadingMessage('unblock');
			//
			createPopUpWindow('editPicture',content, 720, 650);				
		}
	}
}

//preload images plu-in
//usage: preloadImages(img1,img2,img3)
(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preloadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);      
    }
  }
})(jQuery)

function loadingMessage(action,message){
	this.block=function(){
		$.blockUI({ css: { backgroundColor: siteColor.black, color:siteColor.middleGrey, borderWidth:'1px', borderColor:siteColor.middleGrey, borderRadius: '8px'},message: '<img src="/images/loading.gif" /><h3>'+message+'</h3>' } );
	}
	this.unblock=function(){
		$.unblockUI();
	}
	
	if(action=='block'){
		this.block();
	}else{
		this.unblock()
	}
}

function checkDateFormat(date){
	this.enServer=function (){
		var format=/^\d{4}\-\d{1,2}\-\d{1,2}$/;
		if(date.match(format) && date.split('-')[1]<13 && date.split('-')[2]<32){
			return true;
		}else{
			return false;
		}
	}
	this.enHuman=function (){
		var months=Array('none','January','February','March','April','May','June','July','August','September','October','November','December');
		var month=date.split(' ')[0];
		var day=date.split(' ')[1];
		if(day){
			day=day.slice(0,-1);
		}
		var year=date.split(' ')[2];
		if(months.indexOf(month)!=-1 && day<13 && year.length==4){
			return true;
		}else{
			return false;
		}
	}
}

function saveSelection() {
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            var ranges = [];
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                ranges.push(sel.getRangeAt(i));
            }
            return ranges;
        }
    } else if (document.selection && document.selection.createRange) {
        return document.selection.createRange();
    }
    return null;
}

function restoreSelection(savedSel) {
    if (savedSel) {
        if (window.getSelection) {
            sel = window.getSelection();
            sel.removeAllRanges();
            for (var i = 0, len = savedSel.length; i < len; ++i) {
                sel.addRange(savedSel[i]);
            }
        } else if (document.selection && savedSel.select) {
            savedSel.select();
        }
    }
}

//Function to convert hex format to a rgb color
function rgb2hex(rgb){
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 if(rgb){
	 	return "#" +
	  ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
	  ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
	  ("0" + parseInt(rgb[3],10).toString(16)).slice(-2);
 }else{
 	return 'transparent';
 }

}


