function photoPositions() {
	this.positions = new Array();
}

function browseList() {
	this.prev = {
		pid : "",
		ptitle : ""
	};
	this.next = {
		pid : "",
		ptitle : ""
	};
	this.first = {
		pid : "",
		ptitle : ""
	};
	this.last = {
		pid : "",
		ptitle : ""
	};
};

var albumSort = {
	dateView	: 'all',
	attribSort	: 'post_date',
	sortDir		: 'DESC',
	maxItem		: 4
}

var eCode = {
	eWidth : 600,
	eHeight : 350
}

function MetaTags() {
	this.ids = new Array();
	this.tags = new Array();
}

function groupAccess() {
	this.availableGroups = {
		gid : new Array(),
		gname : new Array()
	};
	this.selectedGroups = {
		gid : new Array(),
		gname : new Array()
	};
	
	this.assignDroppables = false;
}


var keyboardAction = function(event) {

        var keycode = event.keyCode;

        var escapeKey;
        if (event.DOM_VK_ESCAPE) {  // mozilla
            escapeKey = event.DOM_VK_ESCAPE;
        } else { // ie
            escapeKey = 27;
        }

        var key = String.fromCharCode(keycode).toLowerCase();
        
		if (keycode == 37) { // load previous photo		
			prevPhoto(event);
        } else if (keycode == 39){ // display next image
        	nextPhoto(event);
        }
}

function nextPhoto(event) {
	if (browseList.next != null) {
		location.href='/photos/'+ curi +'/'+  browseList.next.title + '/' + browseList.next.pid;
	} else {
		location.href='/photos/'+ curi +'/'+ browseList.first.title + '/'+  browseList.first.pid;
		
	}
}

function prevPhoto(event) {
	if (browseList.prev != null) { 
		location.href='/photos/' + curi +'/'+ browseList.prev.title + '/'+ browseList.prev.pid;
    } else {
		location.href='/photos/' + curi +'/' + browseList.last.title + '/'+ browseList.last.pid;	
    }
}

function init() {
	photoBrowse();
	initCommentEvents();
}

function initAlbum() {
	initCommentEvents();
	if (photoEmbed.customizeEmbed == true) {
		configureEmbed();
	}
}

function initCommentEvents() {
	Event.observe($('commentAction'), 'click', displayComments);
	Event.observe($('addComment'), 'click', displayComments);	
}

function finalizeAccessGroups(fn) {
	var aG = groupAccess.availableGroups;
	var sG = groupAccess.selectedGroups;
	var agLen = aG.gid.length;
	var sgLen = sG.gid.length;
	for (i=0; i<agLen; i++) {
		createHiddenInput("groupAccess[availableGroups]["+ aG.gid[i] +"]", aG.gname[i], fn);
	}
	for (i=0; i<sgLen; i++) {
		createHiddenInput("groupAccess[selectedGroups]["+ sG.gid[i] +"]", sG.gname[i], fn);
	}
	fn.submit();
}

function updateSelectedList(ele) {
	var aG = groupAccess.availableGroups;
	var sG = groupAccess.selectedGroups;
	var agLen = aG.gid.length;
	var eid = ele.id.replace(/sGroup_/i, "");
	Droppables.remove($('sGroup_'+ eid));
	
	var sgIndex = sG.gid.indexOf(eid);
    aG.gid[agLen] = sG.gid[sgIndex];
    aG.gname[agLen] = sG.gname[sgIndex];
    sG.gid.splice(sgIndex, 1);
    sG.gname.splice(sgIndex, 1);
    propagateGroups(); 
}

function updateAvailableList(ele) {
	var aG = groupAccess.availableGroups;
	var sG = groupAccess.selectedGroups;
	var sgLen = sG.gid.length;
	var eid = ele.id.replace(/aGroup_/i, "");
	Droppables.remove($('aGroup_' + eid));
 
	var agIndex = aG.gid.indexOf(eid);

    sG.gid[sgLen] = aG.gid[agIndex];
    sG.gname[sgLen] = aG.gname[agIndex];
    aG.gid.splice(agIndex, 1);
    aG.gname.splice(agIndex, 1);
    propagateGroups(); 
    
}

function buildAccessSelection(pA) {
	var aG = groupAccess.availableGroups;
	var sG = groupAccess.selectedGroups;
	if (pA == 0) {
		$('album_access').style.display = "none";
	} else {
		$('album_access').style.display = "";
		if ((aG.gid.length == 0) && (sG.gid.length == 0)) {
			getAvailableGroups();
		}
		if (groupAccess.assignDroppables == false) {
			Droppables.add("availableGroups", {accept: 'selectedGroup', containment: 'selectedGroups', onDrop: updateSelectedList});
			Droppables.add("selectedGroups", {accept: 'selectedGroup', containment: 'availableGroups', onDrop: updateAvailableList});
			groupAccess.assignDroppables = true;
		}
		setTimeout("propagateGroups();", 200);
		
	}
}

function propagateGroups() {

	var aG = groupAccess.availableGroups;
	var sG = groupAccess.selectedGroups;
		$('availableGroups').innerHTML = "";
		$('selectedGroups').innerHTML = "";
		for (var i=0; i<aG.gid.length; i++) {
			var agList = document.createElement("div");
			agList.id = "aGroup_" + aG.gid[i];
			agList.innerHTML = aG.gname[i];
			agList.className = 'selectedGroup';
		
			$('availableGroups').appendChild(agList);
			new Draggable("aGroup_"+ aG.gid[i], {zindex: '9999', revert: true});
		}
		
		for (var i=0; i<sG.gid.length; i++) {
			var sgList = document.createElement("div");
			sgList.id = "sGroup_" + sG.gid[i];
			sgList.className = 'selectedGroup';
			sgList.innerHTML = sG.gname[i];
			$('selectedGroups').appendChild(sgList);
			new Draggable(sgList.id, {zindex: '9999', revert: true});
		}
}

function getAvailableGroups() {
	$('availableGroups').innerHTML = '<img src="/public/shared/images/loading.gif">';
	$('selectedGroups').innerHTML = '<img src="/public/shared/images/loading.gif">';
	var url = '/ajax/getUserFriendGroups.html';
	var myAjax = new Ajax.Request(url, {method: 'post', onComplete: function(obj,json) {
			var json = obj.responseText.evalJSON(true);
			for (var i=0; i<json.groups.length; i++) {
				var aG = groupAccess.availableGroups;
				var aGLen = groupAccess.availableGroups.gid.length;
				if (aG.gid.indexOf(json.groups[i].user_friend_group_id) == -1) {
					aG.gid[aGLen] = json.groups[i].user_friend_group_id;
					aG.gname[aGLen] = json.groups[i].user_friend_group_name;
				}
			}
				
		}	
	});
}

function initTags() {
	var url = '/ajax/getPhotoTags.html';
	var pars = 'album_id='+ album_id;
	var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete: function(obj,json) {
			var json = obj.responseText.evalJSON(true);
			for (var i=0; i<json.photos.length; i++) {
				var thisId = json.photos[i].id;
				var idLen = MetaTags.ids.length;
				MetaTags.ids[idLen] = thisId;
				MetaTags.tags[idLen] = new Array();
				var tagId = MetaTags.tags[idLen];
				
				
				for (var x=0; x<json.photos[i].tags.length; x++) {	
					var tagLen = tagId.length;
					
					tagId[tagLen] = json.photos[i].tags[x];
				}	
				showTags(thisId);
			}
		}
	});
}

function showTags(ids) {
	var metaUL = document.createElement("ul");
	var tagId = MetaTags.tags[MetaTags.ids.indexOf(ids)];
	metaUL.style.margin = "3px";
	metaUL.style.padding = "3px";

	for (var i=0; i<tagId.length; i++) {
		var tag = tagId[i].replace(/(["'\\\\])/g, "\\\\$1").replace(/\\0/g, "\\\\0");
		var metaLI = document.createElement("li");
//		metaLI.style.margin = "3px";
//		metaLI.style.padding = "3px";
		metaLI.innerHTML = tagId[i] + "&nbsp;";
		var metaSpan = document.createElement("span");
		eval("metaSpan.onclick = function() { removeTag('"+ ids +"', '" + tag +"'); };");
		metaSpan.className = "tagRemove";
//		metaSpan.style.border = "solid #000 1px;";
//		metaSpan.style.backgroundColor = "#5F5F5F";
		metaSpan.innerHTML = "&times;";
		metaLI.appendChild(metaSpan);
		metaUL.appendChild(metaLI);
	}
	
	$("tags_container_"+ ids).innerHTML = "";
	$("tags_container_"+ ids).appendChild(metaUL);
}


function addTag(ids) {
	if ($('photo_tags_'+ ids).value == "") return(0);
	var vTags = $('photo_tags_'+ ids).value.split(",");
	
	var tagId = MetaTags.tags[MetaTags.ids.indexOf(ids)];
	if (vTags.length < 1) {
		return(0)
	}
	for (var i=0; i<vTags.length; i++) {
		var thisTag = vTags[i].replace(/^\s+|\s+$/g,"");
		thisTag = thisTag.replace(/"/, "'");
		if (tagId.indexOf(thisTag) == -1) {
			tagId[tagId.length] = thisTag;
		}
	}
	$('photo_tags_'+ ids).value = "";
	showTags(ids);
}

function removeTag(ids, tag) {
	if (tag == "") return(0);
	var tagId = MetaTags.tags[MetaTags.ids.indexOf(ids)];
	var mkIndex = tagId.indexOf(tag);
	if (mkIndex != -1) {
		tagId.splice(mkIndex, 1);
		showTags(ids);
	}
}

function updatePhotos(fn) {
	convertMetaTags2Input(fn);
	fn.submit();
}

function organizePhotos(fn) {
	
	for (i=0; i<photoPositions.positions.length; i++) {
		var photoID = photoPositions.positions[i].replace(/^photo_/, "");
		createHiddenInput("photo_id["+ i +"]", photoID, fn);
	}
	fn.submit();
}

function initPositions() {
	var CN = $('photoList').childNodes;
	Sortable.create('photoList', {overlap: 'horizontal', constraint: false,  onUpdate: function () {
			var CN = $('photoList').childNodes;
			for (i=0; i<CN.length; i++) {
				photoPositions.positions[i] = CN[i].id;
			}		
		}
	});
}

function photoAlbumPagination(currPage) {
	var url = '/ajax/photoAlbumPagination';
	var pars = 'currPage='+ currPage +'&sortCol='+ albumSort.attribSort +'&sortDir=DESC&dateView='+ albumSort.dateView + '&maxItem='+ albumSort.maxItem;
	var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete: function(obj,json) {
			var json = obj.responseText.evalJSON(true);
			//$('pageLink').innerHTML = json.pagination_links;
			$('galleryContents').innerHTML = json.albums;
			$$('.galleries .indicatorsContainer .indicator')[0].innerHTML = json.pagination_links;
		}
	});
}

function sortAlbum(ele, val) {
	if (ele == 'gallerySort') {
		albumSort.attribSort = val;
	}
	if (ele == 'gallerySortTime') {
		albumSort.dateView = val;
	}
	photoAlbumPagination(0,null);
}

function sortAlbumFull(ele, val) {
	if (ele == 'gallerySort') {
		albumSort.attribSort = val;
	}
	if (ele == 'gallerySortTime') {
		albumSort.dateView = val;
	}
	window.location = '/photos/index/'+ albumSort.attribSort +'/'+ albumSort.dateView;
}



function photoBrowse() {
		browseList = br.evalJSON(true);
		document.observe('keydown', keyboardAction);
		
		$$('.imageContainer img')[0].observe('click', nextPhoto).setStyle({cursor: 'pointer'});
}

function photoPopout() {
	window.open('/photos/popPlayer/'+ photoEmbed.Id, 'photoViewer', 'height=390,width=640,toolbar=no,status=no,scrollbars=no,resizeable=yes');
}


function configureEmbed() {
	var pars = 'contType=photo_albums&contId='+ photoEmbed.Id;
	Lightview.show({
	  href: '/ajax/getEmbedCodeForm.html',
	  rel: 'ajax',
	  title: 'Embed This Gallery',
	  options: {

	    topclose: true,
	    ajax: {
	      method: 'post',
	      parameters: pars,
		  onComplete: function() {
					$('theCode').value = generateEmbedCode(photoEmbed.embedWidth, photoEmbed.embedHeight);		
			  		$('embedWidth').value = photoEmbed.embedWidth;
			  		$('embedHeight').value = photoEmbed.embedHeight;
			  		$('videoLink').value = photoEmbed.permalink;
				}
			}
		}
	});			
}

function generateEmbedCode(newWidth, newHeight) {
  	var embdCode = '<object width="'+ newWidth +'" height="'+ newHeight +'"><param name="movie" value="'+ photoEmbed.SwfUrl +'" /><param name="allowfullscreen" value="true" ';
		embdCode += '/><param name="allowscriptaccess" value="always" /><param name="wmode" value="opaque" /><param name="bgcolor" value="#000000" /><param name="flashvars" ';
		embdCode += 'value="config='+ escape(photoEmbed.websiteUrl +'imageConfig/'+ photoEmbed.Id +'.xml') +'" /><embed src="'+ photoEmbed.SwfUrl +'" width="'+ newWidth +'" height="'+ newHeight +'" ';
		embdCode += 'allowfullscreen="true" allowscriptaccess="always" wmode="opaque" bgcolor="#000000" type="application/x-shockwave-flash" ';
		embdCode += 'pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="config='+ escape(photoEmbed.websiteUrl +'imageConfig/'+ photoEmbed.Id +'.xml') +'" ';
		embdCode += 'scale="noscale"></embed></object>';
	
	return (embdCode);
}

function updateEmbed() {
	var currWidth = parseInt($('embedWidth').value);
	var currHeight = parseInt($('embedHeight').value);
	if (currWidth != eCode.eWidth) {
		var oRatio = parseInt(currWidth) / parseInt(photoEmbed.embedWidth);
		eCode.eWidth = currWidth;
		eCode.eHeight = Math.ceil(photoEmbed.embedHeight * oRatio);
		$('theCode').value = generateEmbedCode(currWidth, eCode.eHeight);
		$('embedHeight').value = eCode.eHeight;
	} else if (currHeight != eCode.eHeight) {
		var oRatio = parseInt(currHeight) / parseInt(photoEmbed.embedHeight);
		eCode.eHeight = currHeight;
		eCode.eWidth = Math.ceil(photoEmbed.embedWidth * oRatio);
		$('theCode').value = generateEmbedCode(eCode.eWidth, currHeight);
		$('embedWidth').value = eCode.eWidth;
	}
}


function loadPopout() {
	var flvVideoDiv = document.createElement('div');
	flvVideoDiv.id = 'flashVideo';
	$('popOut').appendChild(flvVideoDiv);
	
	var playerWidth = (photoEmbed.Width != undefined) ? photoEmbed.Width : "640";
	var playerHeight = (photoEmbed.Height != undefined) ? photoEmbed.Height : "390";
	var displayHeight = playerHeight;
	
	var flvVars = {
	      
	        displayheight: '390',
	        enablejs: "true",
	        javascriptid: "bloggermovie",
	        stretching: "uniform",
      		repeat: "none",
	        partnerid: '96',
	        autostart: "false",
	        bufferlength: "2",
	       // albumid: photoEmbed.albumId,
	        config: '/imageConfig/'+ photoEmbed.albumId +'.xml'

	        };
	var flvParams = {
	        allowscriptaccess: "always",
	        allowfullscreen: "true",
	        hideMenu: "true",
	        scale: "default",
	        wmode: "transparent"};
	var attrib = { id: "movie1", name: "movie1" };
	var vidObject = swfobject.embedSWF(photoEmbed.SwfUrl, "flashVideo", "100%", "100%", "9.0.115", "/public/shared/swf/expressInstall.swf", flvVars, flvParams, attrib);
	
	
}
