/**
 * Project Gallery View
 * 
 * Updates the flash module with JSON data from the backend,
 * and changes assocated HTML elements 
 * 
 * @version 0.3 live development
 * @author Avery Brooks <brooks@radicalmedia.com> 
 */
var Gallery = function(_options) {

	// initialization status
	this.initialized = false;

	// this.current = -1;
	
	this.data = {};
	this.cache = {};

	// this.regions = ["USA","UK","AU","DE","CN"];
	this.regions = [];

	// overriden in _options hash
	this.initCallback = function() {return;}
	this.refreshCallback = function() {return;}
	this.selectCallback = function(GroupObjectID) {return;}
	this.pauseCallback = function() {return;}
	this.playCallback = function() {return;}
	
	// default settings
	this.options = {
		downloadURL : false,
		region: false,
		current : 0,
		sidebar : "#item_info",
		links : "#item_links",
		footer : "#video_footer"
	};

	// load options if we have them
	this.setOptions(_options);

}
Gallery.prototype.setOptions = function(_options) {
	if (typeof(_options)!=="object")
		return false;

	for (i in _options) { this.setOption(i,_options[i]); }
	return true;
}
Gallery.prototype.setOption = function(key,val) {

	// optionally return false for rejection of a key, or whatever
	
	switch (key) {

		// These are all exactly the same, so you could really just write
		// something that checks for the suffix, type => function
		// and assigns automatically.
	
		case "initCallback": 
			this.initCallback = val;
			break;

		case "refreshCallback":
			this.refreshCallback = val;
			break;

		case "selectCallback":
			this.selectCallback = val;
			break;

		case "playCallback":
			this.playCallback = val;
			break;

		case "pauseCallback":
			this.pauseCallback = val;
			break;

		// initial data
		case "data":
			this.cache = val;
			this.refreshData();
			// update cache too
			break;

		default:
			this.options[key] = val;
			break;

	}

	return true;
}
Gallery.prototype.init = function() {
	this.initCallback();
	this.initialized = true;
}
Gallery.prototype.select = function(GroupObjectID) {

	var _GV = this;
	
	var item = this.getItem(GroupObjectID);
	if (item === false)
		return false;

	// Sidebar Text
	$(this.options.sidebar).empty();

	if(this.objectHasCopy(item.Copy)) {
		var displayCopy = item.Copy;
	} else if(this.objectHasCopy(this.data.Copy)) { // changed from cache.copy -- need the selected group!
		var displayCopy = this.data.Copy; // changed from cache.copy
	} else {
		var displayCopy = {};
	}

	for(i in displayCopy) {

		// Handle breaks
		var copy = '' + displayCopy[i];
		copy = copy.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + "<br/>" + '$2');

		// Create individual header/link blocks
		$("<div/>")
			.append( $("<h3/>").append( i ) )
			.append( $("<p/>").append( copy ) )
			.appendTo( this.options.sidebar );

	}
	
	// Links
	$(this.options.links).empty();

	var links_area = $("<div/>").appendTo(this.options.links);

	// GROUP alternate download links:
	if (this.data.Attributes.group_dl_high || this.data.Attributes.group_dl_low) {
		
		var download_link = $("<p/>").appendTo(links_area);

		// optional label overrides:
		var download_label = (this.data.Attributes.group_dl_label) ? "Download&nbsp;" + this.data.Attributes.group_dl_label : "Download";

		if (this.data.Attributes.group_dl_high && this.data.Attributes.group_dl_low) {

			// low & hi ?
			$(download_link).append(download_label);
			$("<a/>").attr("href", this.options.downloadURL + this.data.Attributes.group_dl_high).append("&nbsp;&nbsp;HQ").appendTo(download_link);
			$(download_link).append("&nbsp;|&nbsp;");
			$("<a/>").attr("href", this.options.downloadURL + this.data.Attributes.group_dl_low).append("LQ").appendTo(download_link);
		
		} else {

			// low OR hi -- same label
			var VaultID = (this.data.Attributes.group_dl_high) ? this.data.Attributes.group_dl_high : this.data.Attributes.group_dl_low;	
			
			$("<a/>").attr("href", this.options.downloadURL + VaultID).append(download_label).appendTo(download_link);
			
		}
		
	} // end Group alternate download links

	
	
	// ITEM alternate download links:
	var download_link = $("<p/>").appendTo(links_area);

	// optional label overrides:
	var download_label = (item.Attributes.item_dl_label) ? "Download&nbsp;" + item.Attributes.item_dl_label : "Download Item";

	if (item.Attributes.item_dl_high || item.Attributes.item_dl_low) {
		
		// Either both overrides, or one from item / one from override.
		var VaultID_low = (item.Attributes.item_dl_low) ? item.Attributes.item_dl_low : item.VaultID;
		var VaultID_high = (item.Attributes.item_dl_high) ? item.Attributes.item_dl_high : item.VaultID;

		// Low/Hi - ?
		$(download_link).append(download_label);
		$("<a/>").attr("href", this.options.downloadURL + VaultID_high).append("&nbsp;&nbsp;HQ").appendTo(download_link);
		$(download_link).append("&nbsp;|&nbsp;");
		$("<a/>").attr("href", this.options.downloadURL + VaultID_low).append("LQ").appendTo(download_link);

		// everyone but photo gets this:
	} else if (item.VaultID && (main.section !== "PHOTOGRAPHY")) {
		
		// Normal - VaultID from the item
		$("<a/>").attr("href", this.options.downloadURL + item.VaultID).append(download_label).appendTo(download_link);
		
	}

	$("<a/>")
		.append("Email Link")
		.bind("click",function(e){
			e.preventDefault();
			_GV.pauseCallback();
			main.showShareLightBox({
				closeCallback:function(){
					_GV.playCallback();
					return;
				}
			});
		})
		.appendTo(links_area);
		
	$("<a/>")
		.append("Contact Us")
		.bind("click",function(e){
			e.preventDefault();
			_GV.pauseCallback();
			main.showContactLightBox({
				closeCallback:function(){
					_GV.playCallback();
					return;
				}
			});
		})
		.appendTo(links_area);

	$(this.options.footer).empty();

	if (this.regions.length > 0) {

		var regions_float = $("<div>")
			.css("position","absolute")
			.css("bottom","0")
			.css("right","0")
			.appendTo(this.options.footer);
		var regions_area = $("<p>").appendTo(regions_float);

		$(regions_area).append("View as region:&nbsp;&nbsp;");
		
		for(var i = 0; i < this.regions.length; i++) {

			if (i > 0)
				$(regions_area).append(" | ");
			
			// SELECTED ITEM
			if (this.regions[i] == this.options.region) {
				$("<b/>").append(this.regions[i]).appendTo(regions_area);
				continue;
			}
			
			// SELECT REGION LINK
			$("<a/>")
				.attr("rel",this.regions[i])
				.css("cursor","pointer")
				.append(this.regions[i])
				.bind("click",function(e){
					e.preventDefault();
					_GV.setRegion($(this).attr("rel"));
				})
				.appendTo(regions_area);

		}
	}

	// optional credit attribute
	
	var credit = "produced by @radical.media";
	if (item.Attributes.credit) { 
		credit = item.Attributes.credit;
	} else if (this.data.Attributes.credit) {
		credit = this.data.Attributes.credit;
	}

	$("<p>")
		.addClass("produced_by")
		.append(credit)
		.appendTo(this.options.footer);

	this.selectCallback(GroupObjectID);

} // select()
Gallery.prototype.getData = function() {
	return this.data;
}
Gallery.prototype.getItemCount = function() {
	if (!this.cache.SubNav || this.cache.SubNav.length == 0) {
		return this.cache.Items.length;
	} else {
		var l = 0;
		for(var _i=0;_i<this.cache.SubNav.length;_i++) {
			if(this.cache.SubNav[_i].Items.length && this.cache.SubNav[_i].Items.length>l) {
				l = this.cache.SubNav[_i].Items.length;
			}
		}
		return l;
	}
}
Gallery.prototype.getRegionalItemCount = function() {
	return this.data.Items.length;
}
Gallery.prototype.refreshData = function() {
	
	// Partial clone :)

	this.data = {};

	
	// NORMAL MODE -- REGIONS ARE HANDLED W/ ATTRS ON ITEMS
	if (!this.cache.SubNav || this.cache.SubNav.length == 0) {
		var _cache = this.cache;
	
		for (i in _cache) {
			this.data[i] = _cache[i];
		}
		
		this.data.Items = [];
		var regionsTemp = [];
	
		// Limit Items by region - also, while we're looping, grab the region keys
		for(var i = 0; i < this.cache.Items.length; i++) {
	
			if (this.cache.Items[i].Attributes.regions) {
				$.merge(regionsTemp,this.cache.Items[i].Attributes.regions.split(","));
			}
			
			if (this.options.region && this.cache.Items[i].Attributes.regions && !this.cache.Items[i].Attributes.regions.match(this.options.region)) {
				// This item has been inhibited from being added to the gallery
			} else {
				this.data.Items.push(this.cache.Items[i]);
			}
		}
		
		// FUNKY MODE -- REGIONS ARE SUBGROUPS
	} else {

		var regionsTemp = [];
		for(var _i=0;_i<this.cache.SubNav.length;_i++) {
			regionsTemp.push( this.cache.SubNav[_i].Name );
			if (this.getRegion()==this.cache.SubNav[_i].Name) {
				for (i in this.cache.SubNav[_i]) {
					this.data[i] = this.cache.SubNav[_i][i];
				}
			}
		}

	}

	
	// Remove duplicates in the regions
	var a = [];
	var l = regionsTemp.length;
	for(var i=0; i<l; i++) {
		for(var j=i+1; j<l; j++) {
			if (regionsTemp[i] === regionsTemp[j])
				j = ++i;
		}
		a.push(regionsTemp[i]);
	}
	this.regions = a;


	return;
}
Gallery.prototype.getItem = function(GroupObjectID) {
	var test = "";
	for(var i = 0; i < this.data.Items.length; i++) {
		if (GroupObjectID == this.data.Items[i].GroupObjectID)
			return this.data.Items[i];
	}
	return false;
}
Gallery.prototype.setRegion = function(region,no_callback) {
	this.setOption("region",region);
	this.refreshData();
	if (!no_callback) {
		this.refreshCallback();
	}
}
Gallery.prototype.resetRegion = function(no_callback) {
	if (this.regions.length > 0) {
		this.setRegion(this.regions[0],no_callback);
	}
}
Gallery.prototype.getRegion = function() {
	return this.options.region;
}

/**
 * A special note for you:
 * 
 * This function has a confusing name.  What COPY means here
 * is not clone.  It means TEXT.  A better name would be notEmpty()
 * or something like that, b/c all it's doing is checking to see if
 * an object is empty or not
 * 
 * I hope that makes things clearer.  I know, I feel better too.
 */
Gallery.prototype.objectHasCopy = function(obj) {
	var c = 0;
	for (i in obj) { c++; }
	return (c > 0);
}
