function getPreloader(){
	return $('<img class="preloader" src="/images/site/ajax-loader.gif">')
	.css({
		margin:"0 5px"
	});
}
function prependPreLoader(obj){
	var img = getPreloader();
	var currentPL = $(obj).find('.preloader');
	if(currentPL.length <= 0){
		$(obj).prepend(img);
	}
}
function refreshVideoLibrary(a, category){
	/*
	Instead of refreshing the entire thing,
	I'm going to try to only replace the needed sections.
	*/
	if(!category) category = 0;
	//clear the videoLibraryDiv out, and get a new menu ajax style
	prependPreLoader(a);
	
	$.ajax({
		url:'/video_library.php',
		data:{
			menu:1,
			VideoCategoryID:category,
		},
		context:a,
		success:function(data){
			var t = $(this);
			t.find('IMG.preloader').remove();
			
			$('#sub-cat-menu-new-container')
			.find('.unfolded').hide();
			
			var parent = t.parent();
			while(!parent.hasClass("top") && parent.attr("id")!="sub-cat-menu-new-container"){
				parent.show();
				parent = parent.parent();
			}
			
			var childContainer = t.next('ul');
			if(childContainer.length <= 0){
				childContainer = $('<ul></ul>')
				.insertAfter(t);
			}
			
			childContainer.html('').html(data);
			//childContainer.addClass('unfolded');
		},
		error:function(res, e, s){
			console.log("JS Error: "+e.toString());
		}
		
	});
}
function showVideoLibrary(a){
	a = $(a);
	//get all the GET params from the href
	var uri = parseUri(a.attr("href"));
	var data = $.extend({
			content:1,
		},uri.queryKey);
		
	var str="";
	for(var key in data){
		str+= key+" = "+data[key]+"\n";
	}
	//alert(str);
	
	$.ajax({
		url:'/video_library.php',
		data:data,
		success:function(data){
			$('#VideoLibraryContent').html('').html(data);
		},
	});
}
function refreshRegion(billingStateSelect, regionDropDown){
	//This function needs to remake the Billing Region section below based on the state given
	//I need the refereshed version of ShoppingCart and order
	//RegionDropDown is the select that I will empty then fill with proper options

	$.ajax({
		url:'/lib/includes/billing_region.php',
		type:'POST',
		data:{
			refreshState:$(billingStateSelect).val(),
		},
		success:function(data){
			$(regionDropDown).html(data);
			//if the options in this select are one ( the default thing )
			//Then it is not required.
			var options = $(regionDropDown).find('option');
			var required = $(regionDropDown).parent()
				.find('INPUT[name="'+$(regionDropDown).attr("name")+'Required"]')
			if(options.length ==1){
				//not required
				required.remove();
			}else{
				if(required.length < 1){
					required = $('<input type="hidden" '
						+'name="'+$(regionDropDown).attr("name")+'Required" value="1"/>');
					$(regionDropDown).after(required);
				}
			}
		},
	});
}

function CoverFlowImage(leftImage, centerImage, rightImage){
	var me = this;
	me.position = 0;

	me.init = function(){
		me.leftImage = leftImage;
		me.centerImage = centerImage;
		me.rightImage = rightImage;
	}

	
	me.init();
	return me;
}

function CoverFlowGallery(params){
	/*
	
	Images will be positioned absolute and have zIndex to overlap
	
	params
		images - list of CoverFlowImage
		parentObj - where it will be placed
	*/
	var me= this;
	me.images = [];
	me.position = 1;
	me.lastPosition = 0;
	me.maxZindex = 50;
	me.smallImageWidth = 50;
	me.largeImageWidth = 125;
	me.height = 125;


	me.getImage = function(image, imagePos){
		var src, imageWrapper, imageSrc, imageWidth, imageLeft;
		var distance = Math.abs(me.position - imagePos);
		var zindex = me.maxZindex - distance;
		imageWrapper = $('<div class="CoverFlowImage"></div>')
		.css({
			position:"absolute",
			overflow:"hidden",
			top:0,
			left:0,
			zIndex:zindex,
			textAlign:"left",
			opacity:(1 - distance*0.2),
		})
		.data({
			imagePos:imagePos,
		})
		.click(function(){
			me.moveToPos($(this).data("imagePos"));
		});
		
		imageLeft = me.smallImageWidth * imagePos;
		if(me.position != imagePos){
			imageWidth=me.smallImageWidth;
		}else{
			imageWidth=me.largeImageWidth;
		}
		
		//imageLeft needs to increase to the large width
		//after the large one
		if(imagePos > me.position){
			imageLeft = imageLeft + me.largeImageWidth - me.smallImageWidth;
			imageWrapper.css("textAlign", "right");
		}
		
		if(me.position==imagePos){
			src= image.centerImage;
		}else if(me.position > imagePos){
			src= image.leftImage;
		}else if(me.position < imagePos){
			src= image.rightImage;
		}
		
		
		imageWrapper.css({
			width:imageWidth,
			left:imageLeft,
		});
		
		imageSrc = $('<img src="'+src+'" />');
		
		return imageWrapper.append(imageSrc);

	}

	me.moveToPos = function(imagePos){
		//get the right image
		var image, imageObj, lastImage;
		if(me.images[imagePos]){
			//The image it will be
			imageObj = me.images[imagePos];
			image = $(me.parentObj.find('.CoverFlowImage')[imagePos]);
			
			//The image currently selected
			curImageObj = me.images[me.position];
			curImage = $(me.parentObj.find('.CoverFlowImage')[me.position]);
			
			//So, now I have to animate the width of this one to largeImagewidth
			//and whatever the currentPos is to smallwidth
			me.lastPosition = me.position;
			
			curImage.animate({
				width:me.smallImageWidth,
			});
			image.animate({
				width:me.largeImageWidth,
			});
		}
	}

	me.firstRender = function(){
		//Render them all completely
		//Create in specified parentObj
		for(var i=0; i<me.images.length; i++){
			var image = me.images[i];
			image.position = i;
			me.parentObj.append(me.getImage(image, i));
		}
	}
	
	me.init = function(){
		me.images = params.images;
		me.parentObj = $(params.parentObj);
		me.parentObj.css({
			backgroundColor:"black",
			display:"block",
			position:"relative",
			height:me.height,
		});
		me.firstRender();

	}
	me.init();
	
	return me;
}


function GalleryButton(params){
	/*
	params include 
		*nextorprev
		*galleryholder
		amounttoscroll
		buttonheight
	*/
	var buttonheight = 50;
	if(params.buttonheight){
		buttonheight = params.buttonheight;
	}
		
	if(!params.amounttoscroll){
		params.amounttoscroll = $(params.galleryholder).width()*(0.9);
	}
	
	
	var buttonCss = {
		cssFloat:"left",
		width:"10%",
		fontSize:buttonheight,
		marginTop:buttonheight/4,
	}

	var text = "button";
	if(params.nextorprev == "next"){
		text = "&gt;";
	}else{
		text="&lt;";
		//reverse the amountotscroll
		//params.amounttoscroll = parseInt(params.amountoscroll) * (-1);
	}

	var button = $('<a href="">'+text+'</a>')
	.css(buttonCss)
	.data(params)
	.click(function(){
		var g = $(this).data("galleryholder");
		var sl = g[0].scrollLeft;
		
		var newScrollLeft = sl + $(this).data("amounttoscroll");
		if($(this).data("nextorprev") != "next"){
			newScrollLeft = sl - $(this).data("amounttoscroll");
		}
		g.animate({
			scrollLeft:newScrollLeft,
		}, 500);

		return false;
	});
	
	return button;
}

function GalleryHolder(obj, params){
	//Transform obj to Galleryholder
		var buttonheight = 50;
		if(params.buttonheight){
			buttonheight = params.buttonheight;
		}

		var galleryHolder = $("<div ID=\'GalleryHolder\'></div>")
		.css({
			overflow:"hidden",
			width:"70%",
			cssFloat:"left",
		}).insertAfter($("#gallery"));
		
		$("#gallery").appendTo(galleryHolder);

		//The next and previous buttons
		var next, prev;
		next = GalleryButton({
			nextorprev:"next",
			galleryholder:galleryHolder,
			buttonheight:buttonheight,
		});
		next.insertAfter(galleryHolder);

		prev = GalleryButton({
			nextorprev:"prev",
			galleryholder:galleryHolder,
			buttonheight:buttonheight,
		});
		prev.insertBefore(galleryHolder);

		//Everything floating, so i'll clear it to fix that
		next.after($("<br/>").css({
			clear:"left",
		}));

}

// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};
