var webConnexPath = "http://secure.webconnex.com/";
var Video = {'Config':null, 'List':null};

Video.Config = {
	player_path : webConnexPath + 'video/player.swf',
	sample_row_id : 'video_row',
	video_player_id : 'video_player',
	pagination_id : 'pagination',
	per_page : 10
};

Video.List = {
	parent : null,
	sample : null,
	path : null,
	rnum : {},
	data : null,
	

	init : function() { // get sample row and remove it from the document
		
		if( typeof Prototype == 'undefined' ) {
			return false;
		}
		
		var alinks = $$('a'); // Fix all the links on the page so IE doesn't look stupid.. again
		for (var i=0; i < alinks.length; i++) alinks[i].href = alinks[i].href;
		
		var url = document.location.toString();
		this.path = url.substr(0, url.lastIndexOf('/')+1);
		
		var sampleObj = $(Video.Config.sample_row_id);
		
		if( sampleObj == null ) {
			return false;
		}
		
		this.parent = sampleObj.parentNode;
		Element.extend(this.parent);
		this.sample = sampleObj.cloneNode(true);
		sampleObj.remove();
	},
	
	clear : function(alt) {
		var theid = Video.Config.sample_row_id;
		if( typeof alt == 'object' ) {
			theid = alt.id;
		} else if(alt) {
			theid = alt;
		}
		for( var i=1; i<=this.rnum[theid]; i++ ) {
			$(theid + '_' + i).remove();
		}
		this.rnum[theid] = 0;
	},
	
	add : function(data, alt) {
		var altObj = $(alt);
		if( ! altObj ) {
			var sampleObj = this.sample.cloneNode(true);
			if( typeof this.rnum[Video.Config.sample_row_id] == 'undefined' ) this.rnum[Video.Config.sample_row_id] = 0;
			this.rnum[Video.Config.sample_row_id]++;
		} else {
			var sampleObj = altObj.cloneNode(true);
			if( typeof this.rnum[alt] == 'undefined' ) this.rnum[alt] = 0;
			this.rnum[alt]++;
		}	
		var ta = sampleObj.getElementsByTagName('a');
		for( var i=0; i<ta.length; i++ ) {
			var lnk = ta[i].href;
			for( var e in data ) {
				lnk = lnk.replace("{data:"+e+"}", data[e]);
				lnk = lnk.replace("[data:"+e+"]", data[e]);
			}
			ta[i].href = lnk;
		}
		var timg = sampleObj.getElementsByTagName('img');
		for( var i=0; i<timg.length; i++ ) {
			Element.extend(timg[i]);
			var newsrc = timg[i].readAttribute('rsrc').replace(/((?:www|beta|secure)\.)?webconnex\.com/, 'secure.webconnex.com');
			if( newsrc ) {
				for( var e in data ) {
					newsrc = newsrc.replace("{data:"+e+"}", data[e]);
					newsrc = newsrc.replace("[data:"+e+"]", data[e]);
				}
				timg[i].src = newsrc;
				timg[i].removeAttribute('rsrc');
			}
		}
		for( var e in data ) {
			var datTag = "data:"+e;
			var tdat = sampleObj.getElementsByTagName(datTag);
			var keepDefault = false;
			for( var i=0; i<tdat.length; i++ ) {
				var dateAtt = hrefAtt = targetAtt = null;
				var sep = '';
				var elemToInsert = new Array();
				Element.extend(tdat[i]);
				Element.extend(tdat[i].parentNode);
				if( data[e] != '' ) {
					hrefAtt = tdat[i].readAttribute('href');
					dateAtt = tdat[i].readAttribute('date');
					sep = tdat[i].readAttribute('sep');
					if( typeof data[e] != 'object' ) {
						var dataObj = { 0 : data[e] };
					} else if( Object.isArray(data[e]) ) {
						var dataObj = new Object();
						for( var a=0; a<data[e].length; a++ ) dataObj[data[e][a].strip()] = data[e][a];
					} else {
						var dataObj = data[e];
					}
					for( var o in dataObj ) {
						var elmLen = elemToInsert.length;
						if( dateAtt ) {
							var datum = new Date(parseInt(dataObj[o]) * 1000);
							elemToInsert[elmLen] = datum.format(dateAtt);
						} else {
							elemToInsert[elmLen] = dataObj[o];
						}
						if( hrefAtt ) {
							var lnkAtt = {'href':hrefAtt+o};
							if( targetAtt = tdat[i].readAttribute('target') ) {
								lnkAtt.target = targetAtt;
							}
							elemToInsert[elmLen] = new Element('a', lnkAtt).update(elemToInsert[elmLen]);
						}
					}
					for( var el=0; el<elemToInsert.length; el++ ) {
						if( el > 0 ) tdat[i].insert({before:sep});
						tdat[i].insert({before:elemToInsert[el]});
					}
					//tdat[i].insert({before:elemToInsert.join(sep)});
					keepDefault = false;
				} else {
					keepDefault = true;
				}
				if( Prototype.Browser.IE ) { // In IE unknown tags can't have children.. gah..
					var lastSibling = tdat[i].nextSibling;
					var siblingsToRemove = new Array();
					while( lastSibling ) {
						var ieTag = lastSibling.tagName;
						if( ieTag && ieTag.toLowerCase() == '/' + datTag.toLowerCase() ) {
							siblingsToRemove[siblingsToRemove.length] = lastSibling;
							break;
						} else if( keepDefault == false ) {
							siblingsToRemove[siblingsToRemove.length] = lastSibling;
						}
						lastSibling = lastSibling.nextSibling;
					}
					for( var sib=0; sib<siblingsToRemove.length; sib++ ) tdat[i].parentNode.removeChild(siblingsToRemove[sib]);
				} else if( keepDefault == true ) { // Grand children become children
					for( var c=0; c<tdat[i].childNodes.length; c++ ) {
						if( tdat[i].childNodes[c].nodeType == 3 ) {
							tdat[i].insert({before:tdat[i].childNodes[c].data});
						} else {
							tdat[i].insert({before:tdat[i].childNodes[c].cloneNode(true)});
						}
					}
				}
				tdat[i].remove();
			}
		}
		
		
		if( ! altObj ) {
			sampleObj.id += '_' + this.rnum[Video.Config.sample_row_id];
			this.parent.insert(sampleObj);
		} else {
			sampleObj.id += '_' + this.rnum[alt];
			Element.extend(altObj.parentNode);
			altObj.parentNode.insert(sampleObj);
		}
	},
	
	list : function(data, alt) {
		var altObj = $(alt);
		if( ! data ) {
			if( this.data ) {
				data = this.data;
			} else {
				data = {};
			}
		}
		this.data = data;
		if( ! data.pp ) data.pp = Video.Config.per_page;
		Remote.Request('search_videos',
		{
			method:'func',
			parameters : data,
			onSuccess: function(transport){
				var response = transport.responseJSON;
				if( response != null && typeof response == 'object' ) {
					Video.List.clear(alt);
					for( var i=0; i<response.data.length; i++ ) {
						Video.List.add(response.data[i], altObj);
					}
					if( altObj ) altObj.remove();
					var paginate = $(Video.Config.pagination_id);
					if( paginate ) {
						paginate.update(Pagination.generate({'EVENT':Video.List.paginate
															,'FIRST_LAST':true
															,'TOTAL':response.total
															,'PER_PAGE':Video.Config.per_page
															,'WIDE':10
															,'PAGE':response.page
															,'BASE_URL':'#'}));
					}
				}
			},
			onFailure: function(message) {
				alert(message);
			}
		});
	},
	
	paginate : function() {
		Video.List.data.page = this.page;
		Video.List.list();
		return false;
	},
	
	search : function(box) {
		var tbox = $(box);
		this.list({'search':tbox.value, 'userid' : this.data.userid});
	},
	
	show : function(data, similar) {
		Remote.Request('grab_video',
		{
			method:'func',
			parameters : data,
			onSuccess: function(transport){
				var response = transport.responseJSON;
				if( response != null && typeof response == 'object' ) {
					Video.List.add(response);
				}
				var vidPlayer = $(Video.Config.video_player_id);
				if( vidPlayer ) {
					var so = new SWFObject(Video.Config.player_path,'mpl','480','400','9');
					so.addParam('allowscriptaccess','always');
					so.addParam('allowfullscreen','true');
					so.addVariable('file',webConnexPath + 'video/view.php?id=' + response.id);
					if( response.video_logo ) so.addVariable('logo',webConnexPath + "uploads/" + response.video_logo);
					so.addVariable('autostart',true);
					so.addVariable('stretching','fill');
					so.addVariable('width',480);
					so.addVariable('height',400);
					so.write(Video.Config.video_player_id);
				}
				document.title = response.title;
				var embedBox = $('embed_box');
				if( embedBox ) {
					embedBox.value = embedBox.value.replace('{player}', Video.Config.player_path).replace('[player]', Video.Config.player_path);
					embedBox.value = embedBox.value.replace('{video}', webConnexPath + 'video/view.php?id=' + response.id).replace('[video]', webConnexPath + 'video/view.php?id=' + response.id);
				}
				var linkBox = $('link_box');
				if( linkBox ) {
					linkBox.value = window.location;
				}
				if( similar ) {
					Video.List.list({'tag':response.tags, 'pp': 5, 'skip' : response.id, 'userid' : data.userid},similar);
				}
			},
			onFailure: function(message) {
				alert(message);
			}
		});
	}
};

/*
	Extra Required Objects
*/

function wcpng(logo)
{
	var arVersion = navigator.appVersion.split("MSIE");
	var version = parseFloat(arVersion[1]);

	if ((version >= 5.5) && (version < 7.0) && (document.body.filters)) 
	{
		var imgs = [$(logo)];
		for(var i=0; i<imgs.length; i++)
		{
			var img = imgs[i];
			var imgName = img.src.toUpperCase();
			if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
			{
				var imgID = (img.id) ? "id='" + img.id + "' " : "";
				var imgClass = (img.className) ? "class='" + img.className + "' " : "";
				var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
				var imgStyle = "display:inline-block;" + img.style.cssText ;
				if (img.align == "left") imgStyle = "float:left;" + imgStyle;
				if (img.align == "right") imgStyle = "float:right;" + imgStyle;
				if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
				var strNewHTML = "<span " + imgID + imgClass + imgTitle
				+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
				+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
				+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>";
				img.outerHTML = strNewHTML;
				i = i-1;
			}
		}
	}
}

function $G(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return null;
}


var Remote = {
	_requests : null,
	_script : webConnexPath + "video/request.php",
	Request : function(url_or_func, data) {
		if( this._requests == null ) {
			this._requests = new Array();
		}
		var reqLen = this._requests.length;
		this._requests[reqLen] = { 
			onSuccess : data.onSuccess,
			onFailure : data.onFailure
		};
		data.method = data.method.toLowerCase();
		if( data.method == 'func' ) {
			var imp = '&func=' + escape(url_or_func);
		} else {
			var imp = '&url=' + escape(url_or_func);
		}
		var d = new Date();
		$$('head')[0].insert(new Element('script', {id : 'remote_request_script_' + reqLen, type : 'text/javascript',
			src : this._script + '?time=' + d.getTime() + '&req=' + reqLen + imp + '&method=' + escape(data.method) + '&param=' + escape(Object.toJSON(data.parameters))}));

	},
	_callback : function(req, res, header) {
		$('remote_request_script_' + req).remove();
		var data = {
			responseText : res,
			responseXML : null,
			responseJSON : null
		};
		if( header.toUpperCase().indexOf('XML') > -1 ) {
			if( window.ActiveXObject ) {
				var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.async="false";
				data.responseXML = xmlDoc.loadXML(res);
			} else if( window.DOMParser ) {
				var parser = new DOMParser();
				data.responseXML = parser.parseFromString(res,"text/xml");
			}
		} else if ( header.toUpperCase().indexOf('JSON') > -1 ) {
			data.responseJSON = res.evalJSON(true);
		}
		this._requests[req].onSuccess(data);
	},
	_callback_error : function(req, message) {
		if( this._requests[req].onFailure ) this._requests[req].onFailure(message);
	}
};

var Pagination = {
	generate : function(data) {
		var lnk = null;
		if( ! data['TOTAL'] ) data['TOTAL'] = 1;
		if( ! data['PAGE'] ) data['PAGE'] = 1;
		if( ! data['PER_PAGE'] ) data['PER_PAGE'] = 1;
		if( ! data['WIDE'] ) data['WIDE'] = 10;
		if( ! data['SUFFIX'] ) data['SUFFIX'] = '';

		data['RIGHT'] = Math.ceil(data['WIDE'] / 2);
		data['LEFT'] = data['WIDE'] - data['RIGHT'];

		var work = { 'pages' : 0, 'page_span' : new Element('span'), 'st_dots' : null, 'end_dots' : null, 'return' : new Element('span') };

		if( data['TOTAL'] > 0 ) {
			work['pages'] = Math.ceil( data['TOTAL'] / data['PER_PAGE'] );
		} else {
			work['pages'] = 1;
		}

		if( data['PAGE'] && ! data['ST'] ) data['ST'] = (data['PAGE'] * data['PER_PAGE']) - data['PER_PAGE'];
		if( data['ST'] > 0 ) { 
			work['current_page'] = (data['ST'] / data['PER_PAGE']) + 1
		} else {
			work['current_page'] = 1;
		}

		if( data['PAGE'] <= data['LEFT'] ) {
			data['RIGHT'] = data['RIGHT'] + (data['LEFT'] - (data['PAGE'] - 1));
		} else if( (work['pages'] - data['PAGE']) <= data['RIGHT'] ) {
			data['LEFT'] = data['LEFT'] + (data['RIGHT'] - (work['pages'] - data['PAGE']));
		}

		if ( work['current_page'] > 1 ) {
			if( data['PAGE'] > 0 ) {
				var prev = data['PAGE'] - 1;
			} else {
				var prev = data['ST'] - data['PER_PAGE'];
			}			
			var previous_link = new Element('a', {href:data['BASE_URL'] + prev + data['SUFFIX'],title:'Previous Page'}).update("&laquo; BACK");
			if( data['EVENT'] ) previous_link.onclick = data['EVENT'];
			previous_link.page = prev;
		}

		if ( work['current_page'] < work['pages'] ) {
			if( data['PAGE'] > 0 ) {
				var nex = data['PAGE'] + 1;
			} else {
				var nex = data['ST'] + data['PER_PAGE'];
			}
			var next_link = new Element('a', {href:data['BASE_URL'] + nex + data['SUFFIX'],title:'Next Page'}).update("NEXT &raquo;");
			if( data['EVENT'] ) next_link.onclick = data['EVENT'];
			next_link.page = nex;
		}

		if(work['pages'] > 1)
		{			
			for( var i = 0; i <= work['pages'] - 1; i++ )
			{
				var RealNo = i * data['PER_PAGE'];
				var PageNo = i+1;

				if (RealNo == data['ST'])
				{
					work['page_span'].appendChild(document.createTextNode(" " + PageNo));
				}
				else
				{
					work['page_span'].insert(" ");
					if (PageNo < (work['current_page'] - data['LEFT']))
					{
						if( data['FIRST_LAST'] && work['st_dots'] == null )
						{
							var avFirst = Math.round((1+(work['current_page'] - data['LEFT']))/2);
							work['st_dots'] = new Element('span');
							lnk = new Element('a', {href:data['BASE_URL'] + 1 + data['SUFFIX'],title:1}).update(1);
							if( data['EVENT'] ) lnk.onclick = data['EVENT'];
							lnk.page = 1;
							work['st_dots'].insert(lnk);
							work['st_dots'].insert(" ");
							lnk = new Element('a', {href:data['BASE_URL'] + avFirst + data['SUFFIX'],title:avFirst}).update("...");
							if( data['EVENT'] ) lnk.onclick = data['EVENT'];
							lnk.page = avFirst;
							work['st_dots'].insert(lnk);
						}
						continue;
					}

					if (PageNo > (work['current_page'] + data['RIGHT']))
					{
						if( data['FIRST_LAST'] && work['end_dots'] == null )
						{
							var avLast = Math.round((work['pages'] + PageNo) / 2);
							work['end_dots'] = new Element('span');
							lnk = new Element('a', {href:data['BASE_URL'] + avLast + data['SUFFIX'],title:avLast}).update("...");
							if( data['EVENT'] ) lnk.onclick = data['EVENT'];
							lnk.page = avLast;
							work['end_dots'].insert(lnk);
							work['end_dots'].insert(" ");
							lnk = new Element('a', {href:data['BASE_URL'] + work['pages'] + data['SUFFIX'],title:work['pages']}).update(work['pages']);
							if( data['EVENT'] ) lnk.onclick = data['EVENT'];
							lnk.page = work['pages'];
							work['end_dots'].insert(lnk);
						}
						break;
					}
					
					lnk = new Element('a', {href:data['BASE_URL'] + PageNo + data['SUFFIX'],title:PageNo}).update(PageNo);
					if( data['EVENT'] ) lnk.onclick = data['EVENT'];
					lnk.page = PageNo;
					work['page_span'].insert(lnk);
				}
			}

			work['return'].insert(previous_link);
			work['return'].insert(" ");
			work['return'].insert(work['st_dots']);
			work['return'].insert(work['page_span']);
			work['return'].insert(work['end_dots']);
			work['return'].insert(" ");
			work['return'].insert(next_link);
		}
		else if( data['SINGLE_CONTENT'] )
		{
			work['return'].update(data['SINGLE_CONTENT']);
		}

		return work['return'];
	}
};



Date.prototype.format = function(format) {
	var returnStr = '';
	for (var i = 0; i < format.length; i++) {
		var curChar = format.charAt(i);
		if (Date.replaceChars[curChar])
			returnStr += Date.replaceChars[curChar].call(this);
		else
			returnStr += curChar;
	}
	return returnStr;
};
Date.replaceChars = {
	shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
	longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
	longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
	d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
	D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
	j: function() { return this.getDate(); },
	l: function() { return Date.replaceChars.longDays[this.getDay()]; },
	N: function() { return this.getDay() + 1; },
	S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
	w: function() { return this.getDay(); },
	//z: function() { return ""; },
	//W: function() { return ""; },
	F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
	m: function() { return (this.getMonth() < 11 ? '0' : '') + (this.getMonth() + 1); },
	M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; },
	n: function() { return this.getMonth() + 1; },
	t: function() { return ""; },
	//L: function() { return ""; },
	//o: function() { return ""; },
	Y: function() { return this.getFullYear(); },
	y: function() { return ('' + this.getFullYear()).substr(2); },
	a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
	A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
	//B: function() { return ""; },
	g: function() { return this.getHours() == 0 ? 12 : (this.getHours() > 12 ? this.getHours() - 12 : this.getHours()); },
	G: function() { return this.getHours(); },
	h: function() { return (this.getHours() < 10 || (12 < this.getHours() < 22) ? '0' : '') + (this.getHours() < 10 ? this.getHours() + 1 : this.getHours() - 12); },
	H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
	i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
	s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
	//e: function() { return ""; },
	//I: function() { return ""; },
	O: function() { return (this.getTimezoneOffset() < 0 ? '-' : '+') + (this.getTimezoneOffset() / 60 < 10 ? '0' : '') + (this.getTimezoneOffset() / 60) + '00'; },
	//T: function() { return ""; },
	Z: function() { return this.getTimezoneOffset() * 60; },
	//c: function() { return ""; },
	r: function() { return this.toString(); },
	U: function() { return this.getTime() / 1000; }
}