// global flag
var isIE = false;

// global request and XML document objects
var req;
 
// current page of images being viewed
var page = 1;

// current number of images per page
var itemsperpage = 1000;

// total number of images
var totalitems = 0;

// size of images to draw:
var imagesize;
if (ajaxSession['imagesize']!= undefined){
	imagesize=ajaxSession['imagesize'];
} else {
	imagesize = 'small';
}

// list of images
var imagelist;

// lightboxfolder id and location id
var lightboxfolder_id;
var location_id;
var showwatermarks; 

// indicator whether location data has been drawn or not.
var locationdatadrawn = 1;

// This function calls loadXMLDoc(). 
// loadXMLDoc() will call processReqChange() when completed.
// processReqChange() will then call the DrawLocationData() function.
function StartDrawLocationData(thelightboxfolder_id,thelocation_id){

	locationdatadrawn = 0;

	// Load the XML Document.

	lightboxfolder_id = thelightboxfolder_id;
	location_id = thelocation_id;

	//alert('location_edit_location_data_xml.php?lightboxfolder_id=' + lightboxfolder_id + '&location_id=' + location_id);
	loadXMLDoc('lightbox_view_location_data_xml.php?lightboxfolder_id=' + lightboxfolder_id + '&location_id=' + location_id);

}


function trim(s) {
  while (s.substring(0,1) == ' ') {
    s = s.substring(1,s.length);
  }
  while (s.substring(s.length-1,s.length) == ' ') {
    s = s.substring(0,s.length-1);
  }
  return s;
}

function processReqChange() {
	// only if req shows "loaded"
	if (req.readyState == 4) {
		// only if "OK"
		if (req.status == 200) {
			// Do something since the Javascript has been loaded correctly!
			DrawLocationData();
		 } else {
			//alert("There was a problem retrieving the XML data:\n" + req.status + '_' + req.statusText);
		 }
	}
}



// This function uses the XML collected through StartDrawLocationData and starts
// filling in information throughout the page. 
function DrawLocationData(){

	// Generate the Main Description Line.

	var textstring = GetXMLLocData('name');
	var textstring = textstring + '.&nbsp;&nbsp;&nbsp;'+GetXMLLocData('address');
	textstring = textstring + ' ' + GetXMLLocData('city');
	textstring = textstring + ', ' + GetXMLLocData('state_prov');
	textstring = textstring + ' ' + GetXMLLocData('postal_code'); 
	textstring = textstring + '.&nbsp;&nbsp;&nbsp;' +GetXMLLocData('contact_name');
	textstring = textstring + '.&nbsp;&nbsp;&nbsp;' +  GetXMLLocData('phone');
	
	showlocationinfo = GetXMLLocData('showlocationinfo');
	showqatermarks   = GetXMLLocData('showwatermarks');
	
	
	if(showlocationinfo == 'Yes') {
		document.getElementById('xml_addressinformation').innerHTML = textstring;
	}
	
	else{
	    document.getElementById('xml_addressinformation').innerHTML = '';
	}
	
	textstring = GetXMLLocData('contact_name') + ': ';
	textstring = textstring + GetXMLLocData('phone');
	
	if(showlocationinfo == 'Yes') {
		document.getElementById('xml_contact_info').innerHTML = textstring;	
	}
	else{
		document.getElementById('xml_contact_info').innerHTML = '';
	
	}
	// Fill in other areas.
	document.getElementById('xml_imagecount').innerHTML = GetXMLLocData('imagecount') + ' IMAGES&nbsp;';

	// Fill in the Notes Form with Relevant Information.
	document.lightboxfolder_location_notes_form.lightboxfolder_id.value = GetXMLLocData('lightboxfolder_id');
	document.lightboxfolder_location_notes_form.location_id.value       = GetXMLLocData('location_id');
	document.lightboxfolder_location_notes_form.notes.value             = GetXMLLocData('notes');
	document.getElementById('admin_notes').innerHTML                    = '<b> Production Notes: </b> '+ GetXMLLocData('admin_notes');

	// Set whether it is in zone or not.

	document.getElementById('xml_zone').innerHTML = '';
	

	locationList = req.responseXML.getElementsByTagName('locationlist')[0].getElementsByTagName('location');
	locationContent = '<select name="select" style="width:190px;height:17px;font-size: 9px;"  onChange="Javascript:void(StartDrawLocationData('+lightboxfolder_id+',this.options[this.selectedIndex].value)); void(folderFrame.OpenGroupUsingFolderID('+lightboxfolder_id+')); ChangeHighlightedImageFromParent(this.options[this.selectedIndex].value);" >';	
		
	for (k=0; k<locationList.length; k++){
	
		locationContent += '<option value="'+locationList[k].getAttribute('id')+'"'; 
		
		if (location_id == locationList[k].getAttribute('id')){
			locationContent += "SELECTED";
		}
			
		locationContent +=  '>'+locationList[k].getAttribute('name')+ '</option>';

	}	
	locationContent += '</select>';

	document.getElementById('location_dropdown').innerHTML = locationContent;


	bookingStatus= GetXMLLocData('bookingStatus');
	lightboxID= GetXMLLocData('lightboxID');

	bookingStatus= trim(bookingStatus);
	
	bookingContent = '<select name="bookingStatus" style="width:95px;height:17px;font-size: 9px;" onchange="location=this.options[this.selectedIndex].value">';
	
	if (bookingStatus == 'clear'){
		bookingContent+= '<option value="lightbox_view.php?id='+lightboxID+'&booking=clear&lightboxfolder_id='+lightboxfolder_id+'&location_id='+location_id+'#toolBox" SELECTED> cleared';
		bookingContent+= '<option value="lightbox_view.php?id='+lightboxID+'&booking=unclear&lightboxfolder_id='+lightboxfolder_id+'&location_id='+location_id+'#toolBox"> not cleared ';
	}
	
	else if (bookingStatus == 'unclear'){
		
		bookingContent+= '<option value="lightbox_view.php?id='+lightboxID+'&booking=clear&lightboxfolder_id='+lightboxfolder_id+'&location_id='+location_id+'#toolBox"+> cleared  ';
		bookingContent+= '<option value="lightbox_view.php?id='+lightboxID+'&booking=unclear&lightboxfolder_id='+lightboxfolder_id+'&location_id='+location_id+'#toolBox" SELECTED > not cleared';
	}
	
	bookingContent+= '</select>';		

	document.getElementById('xml_booking_status').innerHTML = bookingContent;
	

	// Set whether it is in zone or not.

	document.getElementById('xml_zone').innerHTML = '';
	



	// Set whether it is cleared or not.
	//if (trim(GetXMLLocData('cleared')) == 'Yes'){
//		document.getElementById('xml_cleared').innerHTML = '<b>LOCATION IS CLEARED<b>';
//	} else {
//		document.getElementById('xml_cleared').innerHTML = '<b>LOCATION IS NOT CLEARED</b> ';
//	}

	// Fill in the Download Link on the left side.
	document.getElementById('xml_locationdownload_link').href = 'lightbox_view_location_download.php?lightboxfolder_id=' + lightboxfolder_id + '&location_id=' + location_id; 

	// Fill in the Map Link on the left side.
	document.getElementById('xml_locationmap_link').href = 'map_location.php?id='+location_id+'&lightbox='+lightboxID;

	// Fill in the Location Info Link on the left side.
	showlocationinfo = GetXMLLocData('showlocationinfo');
	if(showlocationinfo == 'Yes') {
		document.getElementById('xml_locationinfo_link').href = 'lightbox_view_location_information.php?lightboxfolder_id=' + lightboxfolder_id + '&location_id=' + location_id; 
	} else {
		document.getElementById('xml_locationinfo_link').innerHTML = '';
	}
	// Fill in the Location Slideshow Link on the left side.
	var link = 'Javascript:void(window.open(\'lightbox_view_slideshow.php?'
	link = link + 'lightboxfolder_id=' + lightboxfolder_id + '&location_id=' + location_id;
	link = link + '\',\'SlideShowPopup\',\'scrollbars=no,width=800,height=660\'));';
	document.getElementById('xml_slideshow_link').href = link;

	// Generate the HTML for the Images.
	imagelist = req.responseXML.getElementsByTagName('imagelist')[0].getElementsByTagName('image');
	totalitems = imagelist.length;
	
	//now that we have a lightbox display subnav
	document.getElementById('thumbNailBox').style.display = "block";	
	
	// Draw the Images Out.		
	DrawImages(page);

	locationdatadrawn = 1;

}

// This function draws all the images into the div.
//
function DrawImages(page){

	// Draw the Items Per Page Selectors.

	DrawItemsPerPage();

	// Draw the Large/Small Images Toggle.
	
	DrawLargeImagesToggle();

	// Draw the Page Throughs.

	if (page < 1) page = 1;
	
	startitem = (page - 1) * itemsperpage;
	enditem = startitem + itemsperpage - 1;
	if (enditem > (totalitems - 1)){
		enditem = totalitems - 1;
	}

	var pages = Math.ceil(totalitems / itemsperpage);

	var minpage = Math.max(1,page - 4);
	var maxpage = Math.min(pages,page + 4 + Math.max(5 - page, 0));

	if (pages > 1){

		// Generate HTML for Pagethrough DIV
	
		var html = '';
		
		if (page > 1){
			html = html + '<a href="Javascript:void(DrawImages(0));"><img src="../images/lightbox/pagethrough-leftleft.png" width="8" height="11" border="0" /></a>';
			html = html + '<a href="Javascript:void(DrawImages(' + (page-1) + '));"><img src="../images/lightbox/pagethrough-left.png" width="8" height="11" border="0" /></a>';
		}
		
		for (i = minpage; i <= maxpage; i++){
		
			start = ( (i - 1) * itemsperpage ) + 1;
			end = start + itemsperpage - 1;
		
			if (i == page){
				html = html + '<a href="Javascript:void(DrawImages(' + i + '));" class="current">' + start + '-' + end + '</a>';
			} else {
				html = html + '<a href="Javascript:void(DrawImages(' + i + '));">' + start + '-' + end + '</a>';
			}
	
		}
	
		if (page < pages){
			html = html + '<a href="Javascript:void(DrawImages(' + (page+1) + '));"><img src="../images/lightbox/pagethrough-right.png" width="8" height="11" border="0" /></a>';
			html = html + '<a href="Javascript:void(DrawImages(' + pages + '));"><img src="../images/lightbox/pagethrough-rightright.png" width="8" height="11" border="0" /></a>';
		}
	
	} else {
	
		html = '';

	}

	document.getElementById('xml_pagethrough').innerHTML = html;


	// Generate HTML for Images DIV

	if (imagesize == 'large'){
		var imagelinksize = '2';
		var theclass = 'thumblarge';
		var	links = '<a href="javascript:void(ToggleLargeImages(\'large\'));" class="current" > 2 </a>'+
				    '<a href="javascript:void(ToggleLargeImages(\'medium\'));" > 3 </a>'+
				    '<a href="javascript:void(ToggleLargeImages(\'small\'));" > 4 </a>';
		
		document.getElementById('xml_images_across').innerHTML = links;	
		
		
	} 
	else if (imagesize == 'medium'){
	
		var imagelinksize = '3';
		var theclass = 'thumbmedium';
		var	links = '<a href="javascript:void(ToggleLargeImages(\'large\'));"> 2 </a>'+
				    '<a href="javascript:void(ToggleLargeImages(\'medium\'));" class="current"> 3 </a>'+
				    '<a href="javascript:void(ToggleLargeImages(\'small\'));"> 4 </a>';
		
		document.getElementById('xml_images_across').innerHTML = links;	
	}
	
	else { 
		var imagelinksize = '4';
		var theclass = 'thumb';
		var	links = '<a href="javascript:void(ToggleLargeImages(\'large\'));"> 2 </a>'+
				    '<a href="javascript:void(ToggleLargeImages(\'medium\'));"> 3 </a>'+
				    '<a href="javascript:void(ToggleLargeImages(\'small\'));" class="current"> 4 </a>';
		
		document.getElementById('xml_images_across').innerHTML = links;		    
	}

	var html = '<table><tr>';	
	for (i = startitem; i <= enditem; i++){
	
		var image_id = imagelist[i].getAttribute('id');
		var image_note = imagelist[i].getAttribute('note');
		var rating = imagelist[i].getAttribute('rating');

		html = html + '<td valign="top"><div class="object">';

        html = html + '<a href="javascript:void(0)" ';

		if (image_note != ''){
			html = html + ' onmouseover="showHideLayers(\'note' + i + '\',\'\',\'show\');" ';
			html = html + ' onmouseout="showHideLayers(\'note' + i + '\',\'\',\'hide\');" ';
		}

		html = html + ' onclick="Javascript:window.open(\'lightbox_view_image_details.php?';
		html = html + 'id=' + image_id + '&imageIndex='+i+'&lightboxfolder_id=' + lightboxfolder_id;
		html = html + '\',\'Popup\',\'scrollbars=yes,width=940,height=810\')" ';
		


	//	html = html + '<a href="lightbox_view_image_details.php?';
	//	html = html + 'id=' + image_id + '&imageIndex='+i+'&lightboxfolder_id=' + lightboxfolder_id + '" target="_blank"';

	//	if (image_note != ''){
	//		html = html + ' onmouseover="showHideLayers(\'note' + i + '\',\'\',\'show\');" ';
	//		html = html + ' onmouseout="showHideLayers(\'note' + i + '\',\'\',\'hide\');" ';
	//	}
		
		html = html + ' title="Click for more information">';
		html = html + '<div class="' + theclass + '">';
		html = html + '<div class="number">' + (i+1) + '</div>';

		if (image_note != ''){
			html = html + '<div class="flag" style="float: left;">';
			html = html + '<div id="note' + i + '" style="visibility: hidden;">' + image_note + '</div>';
			html = html + '</div>';
		}

		html = html + '</div>';
		html = html + '<img src="'+imageurl+'/image_view.php?size=' + imagelinksize + '&id=' + image_id + '&showwatermarks=' +  showwatermarks + '"/></a>';

	   if (imagesize == 'large')
			html = html + '<div id="subTools" style="width:478px">';
		
		else if (imagesize == 'medium')
			html = html + '<div id="subTools" style="width:318px">';
			
	
		else	
			html = html + '<div id="subTools" style="width:237px">';
			
		lightboxID= GetXMLLocData('lightboxID');	
	
		html = html + '<a target="_top" href="lightbox_view.php?id='+lightboxID+'&location_id='+location_id+'&lightboxfolder_id='+lightboxfolder_id+'&imageID='+image_id+'&action=delete#toolBox" title="Delete" id="deleteButton" onclick="return confirm(\'Are you sure you want to delete this image?\');">delete</a>';
				
		html = html + '<div id="ratingStars">';
	
	    index =1;
		
		while(index<6){
			html = html + ' <a href="Javascript:void(0);" onclick="ChangeImageRating('+lightboxfolder_id+','+image_id+ ','+location_id+','+index+');" title="Give image a rating of '+index+'"';
			if (rating>=index){			
				html = html+ 'class="on"';
			} else {
				html = html+ 'class="off"';
			}
			html = html + '></a>';
			
			index++;
	    }
	   html = html +'</div></div></div></td>';
	   
	   	if(i%imagelinksize == imagelinksize-1)
		{
			html += '</tr><tr>';
		}
	}
	html += '</tr></table>'
	document.getElementById('xml_thumbnails').innerHTML = html;

}

// This is a shortcut for getting Location Data out of the XML document in a simple fashion.
function GetXMLLocData(name){
	try {
		var x = req.responseXML.getElementsByTagName(name)[0].firstChild.nodeValue;
	}
	catch(err){
		var x = '';
	}
	return x;
}

// This is a function that saves Location Notes to the server and updates the field using StartDrawLocationData.
function ClearNotes(var1, var2){
	document.lightboxfolder_location_notes_form.notes.value = '';
	SaveNotes(var1, var2);
}

// This is a function that saves Location Notes to the server and updates the field using StartDrawLocationData.
function SaveNotes(var1, var2){

	// Get the Data.
	var lightboxfolder_id = document.lightboxfolder_location_notes_form.lightboxfolder_id.value;
	var location_id = document.lightboxfolder_location_notes_form.location_id.value;
	var notes = document.lightboxfolder_location_notes_form.notes.value;

	var regex = /&/g;
	notes = notes.replace(regex,'%26');

	// Start up the XMLHttpRequest object.

	if (window.XMLHttpRequest) {
		savenotesreq = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		isIE = true;
		savenotesreq = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	savenotesreq.open('POST','lightbox_view_save_location_data.php',false);
	savenotesreq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	savenotesreq.send('lightboxfolder_id=' + lightboxfolder_id + '&location_id=' + location_id + '&notes=' + notes);



	// Make the Dialog Box go away.
	showDialogBox(var1, var2);
	window.frames["locationFrame"].location = "lightbox_view_iframe_locations.php?folderid="+lightboxfolder_id+"&location_id="+location_id;

	return true;

}

// This sets the Items per Page and redraws the images.
function ChangeItemsPerPage(newitemsperpage){

	itemsperpage = newitemsperpage;	// Set the new Items Per Page.
	page = 1;						// Reset to first Page.
	DrawImages(page);				// Draw the Images.

}

// This specifically updates the Images per Page toggles.
function DrawItemsPerPage(){

	var html = '';

	for (i = 1; i <= 3; i++){
		items = i * 12;
		html = html + '<a href="Javascript:void(ChangeItemsPerPage(' + items + '));" ';
		if (itemsperpage == items){ html = html + 'class="current"'; }
		html = html + '>' + items + '</a>';
	}

	html = html + '<a href="Javascript:void(ChangeItemsPerPage(' + totalitems+ '));" ';
		if (itemsperpage == totalitems || (itemsperpage != 12 && itemsperpage != 24 && itemsperpage != 36)){ html = html + 'class="current"'; }
		html = html + '>Show All </a>';

	thediv = document.getElementById('xml_itemsperpage').innerHTML = html;

}

// This specifically updates the Large Image/Small Image toggle.
function DrawLargeImagesToggle(){

	thelink = document.getElementById('xml_largeimages_toggle');	
	thelink.innerHTML = 'Images Across:';
	
}

function ToggleLargeImages(type){

	if (type != '') {
		imagesize= type;
 
	} else { //default to small
		imagesize = 'small';
	}

			
	setSessionValue('imagesize',imagesize,1);
	
	DrawImages(page);

}

function ChangeImageRating(lightboxfolder_id, image_id, location_id, rating){

	loadXMLDoc('lightboxfolder_image_rating_update.php?lightboxfolder_id=' + lightboxfolder_id + '&imageID=' + image_id + '&rating='+rating);
	StartDrawLocationData(lightboxfolder_id, location_id);
			
}

function ChangeLightboxFolderLocationRating(location_id,lightboxfolder_id, rating){

	loadXMLDoc('lightbox_location_rating.php?location_id='+location_id+'&lightboxfolder_id='+lightboxfolder_id+'&rating='+rating); 
	window.location.reload();
}
