/*
* Really easy field validation with Prototype
* http://tetlaw.id.au/view/javascript/really-easy-field-validation
* Andrew Tetlaw
* Version 1.5.4.1 (2007-01-05)
* 
* Copyright (c) 2007 Andrew Tetlaw
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* 
*/
var Validator = Class.create();

Validator.prototype = {
	initialize : function(className, error, test, options) {
		if(typeof test == 'function'){
			this.options = $H(options);
			this._test = test;
		} else {
			this.options = $H(test);
			this._test = function(){return true};
		}
		this.error = error || 'Validation failed.';
		this.className = className;
	},
	test : function(v, elm) {
		return (this._test(v,elm) && this.options.all(function(p){
			return Validator.methods[p.key] ? Validator.methods[p.key](v,elm,p.value) : true;
		}));
	}
}
Validator.methods = {
	pattern : function(v,elm,opt) {return Validation.get('IsEmpty').test(v) || opt.test(v)},
	minLength : function(v,elm,opt) {return v.length >= opt},
	maxLength : function(v,elm,opt) {return v.length <= opt},
	min : function(v,elm,opt) {return v >= parseFloat(opt)}, 
	max : function(v,elm,opt) {return v <= parseFloat(opt)},
	notOneOf : function(v,elm,opt) {return $A(opt).all(function(value) {
		return v != value;
	})},
	oneOf : function(v,elm,opt) {return $A(opt).any(function(value) {
		return v == value;
	})},
	is : function(v,elm,opt) {return v == opt},
	isNot : function(v,elm,opt) {return v != opt},
	equalToField : function(v,elm,opt) {return v == $F(opt)},
	notEqualToField : function(v,elm,opt) {return v != $F(opt)},
	include : function(v,elm,opt) {return $A(opt).all(function(value) {
		return Validation.get(value).test(v,elm);
	})}
}

var Validation = Class.create();

Validation.prototype = {
	initialize : function(form, options){
		this.options = Object.extend({
			onSubmit : true,
			stopOnFirst : false,
			immediate : false,
			focusOnError : true,
			useTitles : false,
			onFormValidate : function(result, form) {},
			onElementValidate : function(result, elm) {}
		}, options || {});
		this.form = $(form);
		if(this.options.onSubmit) Event.observe(this.form,'submit',this.onSubmit.bind(this),false);
		if(this.options.immediate) {
			var useTitles = this.options.useTitles;
			var callback = this.options.onElementValidate;
			Form.getElements(this.form).each(function(input) { // Thanks Mike!
				Event.observe(input, 'blur', function(ev) { Validation.validate(Event.element(ev),{useTitle : useTitles, onElementValidate : callback}); });
			});
		}
	},
	onSubmit :  function(ev){
		if(!this.validate()) Event.stop(ev);
	},
	validate : function() {
		var result = false;
		var useTitles = this.options.useTitles;
		var callback = this.options.onElementValidate;
		if(this.options.stopOnFirst) {
			result = Form.getElements(this.form).all(function(elm) { return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback}); });
		} else {
			result = Form.getElements(this.form).collect(function(elm) { return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback}); }).all();
		}
		if(!result && this.options.focusOnError) {
			Form.getElements(this.form).findAll(function(elm){return $(elm).hasClassName('validation-failed')}).first().focus()
		}
		this.options.onFormValidate(result, this.form);
		return result;
	},
	reset : function() {
		Form.getElements(this.form).each(Validation.reset);
	}
}

Object.extend(Validation, {
	validate : function(elm, options){
		options = Object.extend({
			useTitle : false,
			onElementValidate : function(result, elm) {}
		}, options || {});
		elm = $(elm);
		var cn = elm.classNames();
		return result = cn.all(function(value) {
			var test = Validation.test(value,elm,options.useTitle);
			options.onElementValidate(test, elm);
			return test;
		});
	},
	test : function(name, elm, useTitle) {
		var v = Validation.get(name);
		var prop = '__advice'+name.camelize();
		try {
		if(Validation.isVisible(elm) && !v.test($F(elm), elm)) {
			if(!elm[prop]) {
				var advice = Validation.getAdvice(name, elm);
				if(advice == null) {
					var errorMsg = useTitle ? ((elm && elm.title) ? elm.title : v.error) : v.error;
					advice = '<div class="validation-advice" id="advice-' + name + '-' + Validation.getElmID(elm) +'" style="display:none">' + errorMsg + '</div>'
					switch (elm.type.toLowerCase()) {
						case 'checkbox':
						case 'radio':
							var p = elm.parentNode;
							if(p) {
								new Insertion.Bottom(p, advice);
							} else {
								new Insertion.After(elm, advice);
							}
							break;
						default:
							new Insertion.After(elm, advice);
				    }
					advice = Validation.getAdvice(name, elm);
				}
				if(typeof Effect == 'undefined') {
					advice.style.display = 'block';
				} else {
					new Effect.Appear(advice, {duration : 1 });
				}
			}
			elm[prop] = true;
			elm.removeClassName('validation-passed');
			elm.addClassName('validation-failed');
			return false;
		} else {
			var advice = Validation.getAdvice(name, elm);
			if(advice != null) advice.hide();
			elm[prop] = '';
			elm.removeClassName('validation-failed');
			elm.addClassName('validation-passed');
			return true;
		}
		} catch(e) {
			throw(e)
		}
	},
	isVisible : function(elm) {
		while(elm.tagName != 'BODY') {
			if(!$(elm).visible()) return false;
			elm = elm.parentNode;
		}
		return true;
	},
	getAdvice : function(name, elm) {
		return $('advice-' + name + '-' + Validation.getElmID(elm)) || $('advice-' + Validation.getElmID(elm));
	},
	getElmID : function(elm) {
		return elm.id ? elm.id : elm.name;
	},
	reset : function(elm) {
		elm = $(elm);
		var cn = elm.classNames();
		cn.each(function(value) {
			var prop = '__advice'+value.camelize();
			if(elm[prop]) {
				var advice = Validation.getAdvice(value, elm);
				advice.hide();
				elm[prop] = '';
			}
			elm.removeClassName('validation-failed');
			elm.removeClassName('validation-passed');
		});
	},
	add : function(className, error, test, options) {
		var nv = {};
		nv[className] = new Validator(className, error, test, options);
		Object.extend(Validation.methods, nv);
	},
	addAllThese : function(validators) {
		var nv = {};
		$A(validators).each(function(value) {
				nv[value[0]] = new Validator(value[0], value[1], value[2], (value.length > 3 ? value[3] : {}));
			});
		Object.extend(Validation.methods, nv);
	},
	get : function(name) {
		return  Validation.methods[name] ? Validation.methods[name] : Validation.methods['_LikeNoIDIEverSaw_'];
	},
	methods : {
		'_LikeNoIDIEverSaw_' : new Validator('_LikeNoIDIEverSaw_','',{})
	}
});

Validation.add('IsEmpty', '', function(v) {
				return  ((v == null) || (v.length == 0)); // || /^\s+$/.test(v));
			});

Validation.addAllThese([
	['required', 'This is a required field.', function(v) {
				return !Validation.get('IsEmpty').test(v);
			}],
	['validate-number', 'Please enter a valid number in this field.', function(v) {
				return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v));
			}],
	['validate-digits', 'Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/[^\d]/.test(v);
			}],
	['validate-alpha', 'Please use letters only (a-z) in this field.', function (v) {
				return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Z]+$/.test(v)
			}],
	['validate-alphanum', 'Please use only letters (a-z) or numbers (0-9) only in this field. No spaces or other characters are allowed.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/\W/.test(v)
			}],
	['validate-date', 'Please enter a valid date.', function(v) {
				var test = new Date(v);
				return Validation.get('IsEmpty').test(v) || !isNaN(test);
			}],
	['validate-email', 'Please enter a valid email address. For example fred@domain.com .', function (v) {
				return Validation.get('IsEmpty').test(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v)
			}],
	['validate-url', 'Please enter a valid URL.', function (v) {
				return Validation.get('IsEmpty').test(v) || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v)
			}],
	['validate-date-au', 'Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.', function(v) {
				if(Validation.get('IsEmpty').test(v)) return true;
				var regex = /^(\d{2})\/(\d{2})\/(\d{4})$/;
				if(!regex.test(v)) return false;
				var d = new Date(v.replace(regex, '$2/$1/$3'));
				return ( parseInt(RegExp.$2, 10) == (1+d.getMonth()) ) && 
							(parseInt(RegExp.$1, 10) == d.getDate()) && 
							(parseInt(RegExp.$3, 10) == d.getFullYear() );
			}],
	['validate-currency-dollar', 'Please enter a valid $ amount. For example $100.00 .', function(v) {
				// [$]1[##][,###]+[.##]
				// [$]1###+[.##]
				// [$]0.##
				// [$].##
				return Validation.get('IsEmpty').test(v) ||  /^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/.test(v)
			}],
	['validate-selection', 'Please make a selection', function(v,elm){
				return elm.options ? elm.selectedIndex > 0 : !Validation.get('IsEmpty').test(v);
			}],
	['validate-one-required', 'Please select one of the above options.', function (v,elm) {
				var p = elm.parentNode;
				var options = p.getElementsByTagName('INPUT');
				return $A(options).any(function(elm) {
					return $F(elm);
				});
			}]
]);



function validateAdminSettingForm()
{
	lickey	    = document.getElementById('lickey').value;
	
	if(lickey == "")
	{
		alert('Please enter a valid License Key.'); 
		new Effect.Highlight('licArea' , {endcolor:'#F77B87', restorecolor:'false',duration:1});
		window.scrollTo(1,1);
		return false;
	}
	
	
	siteName	    = document.getElementById('sitename').value;
	
	if(siteName == "")
	{
		alert('Please enter a valid Site Name.'); 
		new Effect.Highlight('siteNameArea' , {endcolor:'#F77B87', restorecolor:'false',duration:1});
		window.scrollTo(1,1);
		return false;
	}	
	
	domainName	    = document.getElementById('domain').value;
	 
	if(domainName == "")
	{
		alert('Please enter a valid Domain Name.'); 
		new Effect.Highlight('domainNameArea' , {endcolor:'#F77B87', restorecolor:'false',duration:1});
		window.scrollTo(1,1);
		return false;
	}	
	
	pathName	    = document.getElementById('path').value;
	
	if(pathName == "")
	{
		alert('Please enter a valid Path Name.'); 
		new Effect.Highlight('pathNameArea' , {endcolor:'#F77B87', restorecolor:'false',duration:1});
		window.scrollTo(1,1);
		return false;
	}	
	
	ffmpegPath	    = document.getElementById('ffmpeg_path').value;
	
	if(ffmpegPath == "")
	{
		alert('Please enter a valid FFMPEG Path.'); 
		new Effect.Highlight('ffmpegPath' , {endcolor:'#F77B87', restorecolor:'false',duration:1});
		window.scrollTo(1,1);
		return false;
	}

	ffmpegLimit	    = document.getElementById('ffmpeg_limit').value;
	
	if(ffmpegLimit == "" || ffmpegLimit <= 0)
	{
		alert('Please enter a valid FFMPEG Limit.'); 
		new Effect.Highlight('ffmpegLimit' , {endcolor:'#F77B87', restorecolor:'false',duration:1});
		window.scrollTo(1,1);
		return false;
	}
	
	flvtool2_path	    = document.getElementById('flvtool2_path').value;
	
	if(flvtool2_path == "")
	{
		alert('Please enter a valid FLV Tool Path.'); 
		new Effect.Highlight('flvToolPath' , {endcolor:'#F77B87', restorecolor:'false',duration:1});
		window.scrollTo(1,1);
		return false;
	}
	
	im_path	    = document.getElementById('im_path').value;
	
	if(flvtool2_path == "")
	{
		alert('Please enter a valid ImageMagick Path.'); 
		new Effect.Highlight('imPath' , {endcolor:'#F77B87', restorecolor:'false',duration:1});
		window.scrollTo(1,1);
		return false;
	}
	
	wget_path	    = document.getElementById('wget_path').value;
	
	if(flvtool2_path == "")
	{
		alert('Please enter a valid ImageMagick Path.'); 
		new Effect.Highlight('wgetPath' , {endcolor:'#F77B87', restorecolor:'false',duration:1});
		window.scrollTo(1,1);
		return false;
	}
	
	dlLimit	    = document.getElementById('limit').value;
	
	if(dlLimit == "" || dlLimit <= 0)
	{
		alert('Please enter a valid Download Limit greater than 0.'); 
		new Effect.Highlight('dlLimit' , {endcolor:'#F77B87', restorecolor:'false',duration:1});
		window.scrollTo(1,1);
		return false;
	}
	
	hs	    		= document.getElementById('hs').checked;
	hostedServer	= document.getElementById('hostedServer').value;
	 
	if(hs && hostedServer == "")
	{
		alert('Please enter a valid Hosted Server URL.'); 
		new Effect.Highlight('hostedServerArea' , {endcolor:'#F77B87', restorecolor:'false',duration:1});
		window.scrollTo(1,1);
		return false;
	}
	
	tpp	    = document.getElementById('thumbs_perpage').value;
	
	if(tpp == "" || tpp <= 0)
	{
		alert('Please enter how many videos will be displayed on the main pages.'); 
		new Effect.Highlight('tppArea' , {endcolor:'#F77B87', restorecolor:'false',duration:1}); 
		return false;
	}
	
	catPaginate = document.getElementById('catPaginate').value;
	itemsPerCat = document.getElementById('items_percatpage').value;
	
	if(catPaginate == 'yes' && itemsPerCat <= 0)
	{
		alert('Please enter how many categories you want listed per page.'); 
		new Effect.Highlight('items_percatpageRow' , {endcolor:'#F77B87', restorecolor:'false',duration:1});
		return false;
	}
	  
	
	tags_perpage	    = document.getElementById('tags_perpage').value;
	
	if(tags_perpage == "" || tags_perpage <= 0)
	{
		alert('Please enter how many categories will be displayed in each tag cloud.'); 
		new Effect.Highlight('tagCArea' , {endcolor:'#F77B87', restorecolor:'false',duration:1}); 
		return false; 
	}
	
	desc_length	    = document.getElementById('desc_length').value;
	
	if(desc_length == "" || desc_length < 0)
	{
		alert('Please enter the length allowed for video descriptions.'); 
		new Effect.Highlight('thumbDArea' , {endcolor:'#F77B87', restorecolor:'false',duration:1}); 
		return false; 
	}
	
	vid_width	    = document.getElementById('vid_width').value;
	
	if(vid_width == "" || vid_width <= 0)
	{
		alert('Please enter the width of the video player.'); 
		new Effect.Highlight('playerWidth' , {endcolor:'#F77B87', restorecolor:'false',duration:1}); 
		return false; 
	}
	
	vid_height	    = document.getElementById('vid_height').value;
	
	if(vid_height == "" || vid_height <= 0)
	{
		alert('Please enter the height of the video player.'); 
		new Effect.Highlight('playerHeight' , {endcolor:'#F77B87', restorecolor:'false',duration:1}); 
		return false; 
	}
	
    img_width	    = document.getElementById('img_width').value;
	
	if(img_width == "" || img_width <= 0)
	{
		alert('Please enter the width of each image.'); 
		new Effect.Highlight('imgWidth' , {endcolor:'#F77B87', restorecolor:'false',duration:1}); 
		return false; 
	}
	
	img_height	    = document.getElementById('img_height').value;
	
	if(img_height == "" || img_height <= 0)
	{
		alert('Please enter the height of each image.'); 
		new Effect.Highlight('imgHeight' , {endcolor:'#F77B87', restorecolor:'false',duration:1}); 
		return false; 
	}
	
	cat_img_width	    = document.getElementById('cat_img_width').value;
	
	if(cat_img_width == "" || cat_img_width <= 0)
	{
		alert('Please enter the witdth of each category image.'); 
		new Effect.Highlight('catWidth' , {endcolor:'#F77B87', restorecolor:'false',duration:1}); 
		return false; 
	}
	
	cat_img_height	    = document.getElementById('cat_img_height').value;
	
	if(cat_img_height == "" || cat_img_height <= 0)
	{
		alert('Please enter the witdth of each category image.'); 
		new Effect.Highlight('catHeight' , {endcolor:'#F77B87', restorecolor:'false',duration:1}); 
		return false; 
	}
	 
}



function toggleMassEditForm(value)
{ 
	if(value == 5 )
	{ 
		document.getElementById('massEditAdditionOptions').style.display = 'none';
		document.getElementById('deThumbWarning').style.display = 'none';
		document.getElementById('thumbsOptions').style.display = '';  
	}
	else if(value == 6 )
	{
		document.getElementById('massEditAdditionOptions').style.display = 'none';
		document.getElementById('thumbsOptions').style.display = 'none';
		document.getElementById('deThumbWarning').style.display = '';
	}
	else 
	{	
		document.getElementById('thumbsOptions').style.display = 'none';
		document.getElementById('deThumbWarning').style.display = 'none'; 
		document.getElementById('massEditAdditionOptions').style.display = '';
	}
		
}

function toggleClipsThumbs()
{
	if(document.getElementById('toggleThumb').style.display == '')
	{ 
		document.getElementById('toggleClipThumbText').innerHTML = 'Show Thumbs';
		new Effect.Shrink('toggleThumb');
		setTimeout("new Effect.Grow('toggleClip');",150);
	}
	else
	{
		document.getElementById('toggleClipThumbText').innerHTML = 'Show Clips';
		new Effect.Shrink('toggleClip');
		setTimeout("new Effect.Grow('toggleThumb');",150); 
	}
}

function togglePreviewPic(src)
{ 
 
	
	document.getElementById('previewPic').innerHTML = '<img src="'+src+'" width="200">'; 
 
	new Effect.SlideUp('delThumbsArea',{ duration: 1.0 });
	  
}


function confirmRemoveThumbnail(id,filename,channel,tag,divid,loc,kind)
{
	answer = confirm("Continue To Delete Clip");
	
	if( answer )
	{
		data = "deleteThumbnail=1&videoId="+id+"&channel="+channel+'&tag='+tag+"&rf="+filename; 
		
 		var xmlhttp = web_request();
	
		xmlhttp.onreadystatechange = function() {

		if(xmlhttp.readyState == 4) 
		{ 
			one    = xmlhttp.responseText.substr(0,xmlhttp.responseText.indexOf("*")); 
			cut    = xmlhttp.responseText.substr(xmlhttp.responseText.indexOf("*")+1);
			
			two    = cut.substr(0,cut.indexOf("*"));  
			cut    = cut.substr(cut.indexOf("*")+1);
			
			three  = cut.substr(0,cut.indexOf("*")); 
			four   = cut.substr(cut.indexOf("*")+1); 
				
			if(one != 1 && one != 2 && one != "")
			{	 
				img = '<img src="'+loc+one+'" width="200">'; 
				document.getElementById('previewPic').innerHTML = img; 
			}
			  
			if(two != 1 && two != "")    
				document.getElementById(kind+'Delete-'+two).style.display = 'none';  
			 
			if(three)
				document.getElementById('selectThumb').innerHTML = three; 
				
			
			if(four && kind == 'thumb')
			{	
				
					
				if(four.indexOf('.') == -1)
				{
					s = (four > 1)?"s":"";
				 document.getElementById('delThumbCount').innerHTML = four+' Available Thumb'+s; 
				}
				else
					document.getElementById('delThumbCount').innerHTML =  '1 Available Thumb';
				 
			}
			
			
			document.getElementById(kind+'-'+divid).style.display = 'none';
		 
			
		}		

	}

	xmlhttp.open("GET", 'process_ajax.php?' + data, true);
	xmlhttp.send(null);
	}
}


function confirmDeleteThumbs(id,channel,tag)
{
	 
	
	answer = confirm("Continue To Delete ALL Thumbs");
	if(answer)
	{
		data = "deleteThumbs=1&videoId="+id+"&channel="+channel+"&tag="+tag+"&reselect=1"; 
		
 		var xmlhttp = web_request();
	
		xmlhttp.onreadystatechange = function() {

		if(xmlhttp.readyState == 4) 
		{
			document.getElementById('toggleClipThumbText').innerHTML = 'Show Clips';
			if(document.getElementById('toggleThumb').style.display == '')
				new Effect.Shrink('toggleThumb');
			else
				new Effect.Shrink('toggleClip');
			setTimeout('document.getElementById("toggleThumb").style.display = "none";',1000);
			document.getElementById('toggleThumb').innerHTML = "";
			document.getElementById('toggleThumb').innerHTML += '<div id="thumblist" style="overflow:hidden;">';
			document.getElementById('toggleThumb').innerHTML += '<ul class="img">';
			document.getElementById('toggleThumb').innerHTML += '<div style=""><img src="thumbs/naimage.jpg" id="playlistthumbs"  width="100" height="100"/><div class="clip" style="height:15px;"></div></div><br>';
			document.getElementById('toggleThumb').innerHTML += '</ul>';
			document.getElementById('toggleThumb').innerHTML += '</div>';
			document.getElementById('toggleThumb').innerHTML += '</div>';
				
			//'<div style=""><img src="thumbs/naimage.jpg" id="playlistthumbs"/><div class="clip" style="height:15px;"></div></div><br>'
			setTimeout("new Effect.Grow('toggleThumb');",1000);
			 
			src = xmlhttp.responseText.substr(0,xmlhttp.responseText.indexOf("*"));
			
			select = xmlhttp.responseText.substr(xmlhttp.responseText.indexOf("*")+1);
			 
		 	if(src != 'unchanged')   
		 		document.getElementById('previewPic').innerHTML = '<img src="'+src+'" width="200">'; 
		 	 
		 	 
		    	 
		    document.getElementById('selectThumb').innerHTML = select; 
 
			new Effect.SlideUp('delThumbsArea',{ duration: 1.0 });
			 
			
			
		}		

	}

	xmlhttp.open("GET", 'process_ajax.php?' + data, true);
	xmlhttp.send(null);
	}
}


function getIsCronRunning(time)
{
	 
	data = "isCronRunning=1"; 
	var xmlhttp = web_request();
	 
	xmlhttp.onreadystatechange = function() 
	{

		if(xmlhttp.readyState == 4) 
		{ 
			 
			ret = xmlhttp.responseText;
			if(ret == 'true')
			{
				try
				{
					getID = document.getElementById('settingsLink');
					add = "new Effect.Highlight('settingsLink' , {startcolor:'#F77B87', restorecolor:'true',duration:1});"; 
					add += "getIsCronRunning(2000);";
				}
				catch(err){ add = "";}
				
				 
				
			}
			else
				add = "";
			
			setTimeout(add,time);
		}
		
	}
	
	xmlhttp.open("GET","process_ajax.php?"+data,true);
	xmlhttp.send(null);
	
	
	
} 



function getQueueStatus(time)
{
	 
	data = "queueStatus=1"; 
	var xmlhttp = web_request();
	 
	xmlhttp.onreadystatechange = function() 
	{

		if(xmlhttp.readyState == 4) 
		{ 
			src = xmlhttp.responseText.substr(0,xmlhttp.responseText.indexOf("*"));
			ret = xmlhttp.responseText.substr(xmlhttp.responseText.indexOf("*")+1);
			if(ret == 'true')
			{
				add = "document.getElementById('innerQueueStatus').style.backgroundColor ='#cecece';"; 
				add = "new Effect.Highlight('statusTitle' , {startcolor:'#F77B87', restorecolor:'true',duration:1});"; 
				add += "getQueueStatus(2000);";
			}
			else
				add = "";
			 
				text = '<div id="statusTitle" class="titleSetting" style="margin-top:5px;background-color:">Queue Status</div><div class="inner" >&raquo; <a href="index.php?settings=qStatus&q=imports">Imports</a> 0 </div><div class="inner" >&raquo; <a href="index.php?settings=qStatus&q=thumbs">Thumbs</a> 0 </div><div class="inner" > &raquo; <a href="index.php?settings=qStatus&q=spider">Spider</a> 0 </div>';
				src = (src.length <= 1)?text:src;
				setTimeout("document.getElementById('qStatus').innerHTML = '"+src+"';"+add,time);
			 
		}
		
	}
	
	xmlhttp.open("GET","process_ajax.php?"+data,true);
	xmlhttp.send(null);
	
	
	
} 


function validateRethumbing(duration)
{ 
	
	try
	{
		snapshot = document.getElementById("snapshot").value; 
	}
	catch(e)
	{
		return true;
	}
		 
	if(duration > 0)
	{
		if(duration == null || duration <= 0 ) 
			err = (snapshot > 0)?true:false; 
		else 
			err = (snapshot > 0 && snapshot != duration)?true:false;
			 
		 
 
	}
	else
		err = (snapshot > 0 )?true:false;
		
	if(!err) 
		alert('Thumb Creation input is invalid.\nPlease check the input and try again.');
		   
	
	return err;
}

function updatePreviewPic(vid,loc,filename)
{
	 
	answer = confirm("Update Preview Pic?");
	if(answer)
	{
		data = "updatePreviewPic=1&videoID="+vid+"&filename="+filename; 
		
 		var xmlhttp = web_request();
	
		xmlhttp.onreadystatechange = function() {

		if(xmlhttp.readyState == 4) 
		{ 
		 	 document.getElementById('previewPic').innerHTML = '<img src='+loc+filename+' width=200>'; 
		}		 
		
	}

	xmlhttp.open("GET", 'process_ajax.php?' + data, true);
	xmlhttp.send(null);
	}
}

function showRethumbFields(arg)
{ 
	document.getElementById('thumbArea').innerHTML = (arg == 2) ?
			'<input type="text" name="snapshot" id="snapshot" value="3" size="1" maxlength="3"> seconds into clip':
			(arg == 3)?'1 image for every <select name="snapshot" id="snapshot"><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option><option value="18">18</option><option value="19">19</option><option value="20">20</option></select> seconds':''; 
			// <input type="text" name="snapshot" id="snapshot" value="10" size="2" maxlength="2"> 
}


 
function validateElements()
{
	
	try
	{
		i = 0;
		for(i;true;i++)
		{
			document.getElementById('elementMappingSelector_'+i).value;
		}
		
	}
	catch(e)
	{
		num = i;
	}
	if(num > 1)
	{
		foundFLV = false;
		for(i=0;i<num;i++)
		{
			 
			idi = document.getElementById('elementMappingSelector_'+i).value;
			
			if(!foundFLV && idi == 'flvurl')
				foundFLV = true;
				
			for(j=0;j<num;j++)
			{
				
				if(i!=j && idi != 'none')
				{
					idj = document.getElementById('elementMappingSelector_'+j).value;
					if(idj == idi)
					{
						alert('It appears one or more of the elements identified are the same. \n Please make sure each element you select is unique from one another.\n N/A elements do no apply.');
						return false;
					}
				}
			}
		}
		if(!foundFLV)
		{
			alert('No FLV URL found. Please choose an element as an FLV URL.')
			return foundFLV;
		}
		else return foundFLV;
	}
	else
	{
		ret = true;
		//alert("validateElements="+ret);
		return ret;
	}
}


function addslashes(str) {

str=str.replace(/'/g,"");


return str;
}

function IsNumeric(inputVal) {
     if (isNaN(parseFloat(inputVal))) {
         
          return false;
     }
     return true
}


function showElements()
{
	 
	area		= document.getElementById('elementMappingDisplay');
	output		= "";
	total		= "";
	num			= 0;
	
	
	file 		= document.getElementById('file').value;
	file 		= (file.indexOf('\n') > 0)?file.substring(0,file.indexOf('\n')):file;
	
	 
	elements 	= file.split("|");
	
	size		= elements.length; 
	 
	replace     = "**********";
	
	replaceImg  = "**img**";
	replaceDsc  = "**dsc**";
	replaceCat  = "**cat**";
	replaceNan  = "**nan**";
	
	imgElementSet = false;
	
	
	if(size >= 1 && size < 10 && file.length != 0)
	{ 
		output	+= "<hr><table bgcolor='cedede'><tr><td align='left'><b> Detected "+replace+"</b></td></tr></table>";
		
		for(i=0;i<size;i++)
		{
			output	+= "<table bgcolor='dedede'>"; 
			elements[i] = addslashes(elements[i]);
			toLower = elements[i].toLowerCase();
			
			flvElement = (toLower.indexOf('.flv') > 0)?" selected ":null;
			
			imgElement = (toLower.indexOf('.jpg') > 0)?" selected ":null;
			imgElement = (imgElement)?imgElement:(toLower.indexOf('.gif') > 0)?" selected ":null;
			
			catElement = (toLower.indexOf(',') > 0)?" selected ":null;
			
			dscElement = (!catElement && toLower.indexOf(' ') > 0)?" selected ":null;
			
			durElement = (IsNumeric(elements[i]) == true)?" selected ":null;
			
			nanElement = (!flvElement &&!imgElement &&!catElement &&!dscElement)?" selected ":null;
			
			if(imgElement && !imgElementSet)imgElementSet = true;
			
			if(elements[i].length > 0)
			{
				output	+= "<tr>";
				output	+= " <td>";
				output	+= 	"<select onchange='' id='elementMappingSelector_"+i+"' name='elementMappingSelector_"+i+"' style='font-size:8pt'>";
				output	+= 	" <option value='flvurl' "+flvElement+">FLV URL</option>";
				output	+= 	" <option value='imgurl' "+replaceImg+" "+imgElement+">IMG URL</option>";
				output	+= 	" <option value='desc' "+replaceDsc+" "+dscElement+">DESCRIPTION</option>";
				output	+= 	" <option value='cats' "+replaceCat+" "+catElement+">CATEGORIES</option>";
				output	+= 	" <option value='dur' "+durElement+">DURATION (SEC)</option>";
				output	+= 	" <option value='none' "+replaceNan+" "+nanElement+">N/A</option>";
				output	+= 	" </select>";
				output	+= 	"</td>";
				output	+= " <td><input type='text' value='"+elements[i]+"' style='font-size:8pt' size='110'></td>";
				output	+=  "</tr>";
				
				num++;
			}
			output	+= "</table>";
			
		}
		 
		 
		output	+= "<table bgcolor='cedede'><tr><td align='left'><input type='submit' name='import_submit' value='Import'/><input type='hidden' name='elementMappingSubmit' value='1'></td></tr></table>";
	 	
		
		
		if(num == 1)
		{
			output = output.replace(replaceImg,"disabled");
			output = output.replace(replaceDsc,"disabled");
			output = output.replace(replaceCat,"disabled");
			output = output.replace(replaceNan,"disabled"); 
			total  = num+" Element";
		}
		else
		{
			
			total  = num+" Elements";
		}
		
		for(i=0;i<=num;i++)
		{
			output = output.replace(replace,total); 
			output = output.replace(replaceImg,"");
			output = output.replace(replaceDsc,"");
			output = output.replace(replaceCat,"");
			output = output.replace(replaceNan,"");
		}
		 
				
		//alert(output);
		area.innerHTML = output;
		
		document.getElementById('import_process').innerHTML = '<input type="button" name="" value="Reprocess" onclick="showElements()"/>';
		
		if( document.getElementById('thumbCreation').options[0].selected && !imgElementSet)
		{
			document.getElementById('thumbCreation').options[1].selected = true;
			document.getElementById('thumbArea').innerHTML = '<input type="text" name="snapshot" id="snapshot" value="3" size="1" maxlength="3"> seconds into clip';
			alert('No Image Element could be found.\nThumb Creation has been set to Single');
		}
	}
	else 
	{
		if(size >= 5)
			alert('You entered a FLV File with too many elements.\nPlease check the file and try again.');		
		else if(size <= 1)
			alert('Please Enter A Valid FLV Import File');
	}
	 
	
}

function showLimits(arg)
{
	area = document.getElementById('limitsArea');
	area.innerHTML = '';
	html = "<table bgcolor='#cecece' cellspacing=1 cellpadding=1 border=0><tr><td width='10%'><b>Start</b></td><td><input type='text' size='2' name='start' id='start' maxlength='3' value='0'></td></tr><tr><td><b>Stop</b></td><td><input type='text' size='2' name='limit' id='limit' maxlength='3' value='50'></td></tr></table>";
	if(arg == 'on')
		area.innerHTML = html;
	else if(arg == 'off')
		area.innerHTML = '<input type=hidden name=recent value=1>';
}

function CategoryRequestNotActive(data, id) {
	var url = 'process_ajax.php';
	var yes = confirm("Are you Sure? OK To Continue");
		if (yes == true) {
			var perform = new Ajax.Request(url, {method:'get', parameters: data} );
			document.getElementById(id).style.display = 'none';
		} 
}

/** For matching category */
function CategoryMatchRequestNotActive(data, id) {
	var url = 'process_ajax.php';
	var pars = 'select_notactive='+$F(data);
	var yes = confirm("Use This Category? OK To Continue");
	if (yes == true) {
		var perform = new Ajax.Request(url, {method:'get', parameters: pars} );
		document.getElementById(id).style.display = 'none';
	}
}

function CheckDataAutoUpdate() {
	
	if(document.getElementById('dump_url').value == '') {
		alert('Please Enter Dump URL');
		document.getElementById('dump_url').focus();
		return false;
	}
	
	var frequency = document.getElementById('frequency');
	if(frequency.options[frequency.selectedIndex].value == '') {
		alert('Please Choose Frequency');
		return false;
	}
	
	var channel = document.getElementById('channel');
	if(channel.options[channel.selectedIndex].value == '') {
		alert('Please Choose Channel');
		return false;
	}
	
	var channel = document.getElementById('type');
	if(channel.options[channel.selectedIndex].value == '') {
		alert('Please Choose Type');
		return false;
	}
	
	var channel = document.getElementById('insertion');
	if(channel.options[channel.selectedIndex].value == '') {
		alert('Please Choose Insertion Type');
		return false;
	}
	
	var channel = document.getElementById('img_type');
	if(channel.options[channel.selectedIndex].value == '') {
		alert('Please Choose Image Type');
		return false;
	}
}

function CheckDataImport() {	
	var retValue = true;
	var channel  = document.getElementById('channel');
	if(channel.options[channel.selectedIndex].value == '') {
		alert('Please Choose Channel');
		retValue = false;
	} 
	
	if(document.getElementById('file').value == '') {
		alert('Please Enter Dump File');
		document.getElementById('file').focus();
		retValue = false;
	}
	
	//alert("CheckDataImport="+retValue);
	return retValue;
}

function CheckDataXMLImport() {	
	var channel = document.getElementById('channel');
	if(channel.options[channel.selectedIndex].value == '') {
		alert('Please Choose Channel');
		return false;
	} 
	
	if(document.getElementById('url').value == '') {
		alert('Please enter a Valid URL');
		document.getElementById('url').focus();
		return false;
	}
}


/** To check data on auto update */
function CheckDataEmbed() {
		
	var channel = document.getElementById('channel');
	if(channel.options[channel.selectedIndex].value == '') {
		alert('Please Choose Channel');
		return false;
	}
	
	var image = document.getElementById('img_type');
	if(image.options[image.selectedIndex].value == 'url') {
		if(document.getElementById('imageUrlData').value == '') {
			alert('Please Enter Image Url');
			document.getElementById('imageUrlData').focus();
			return false;
		}
	} else {
		if(document.getElementById('imageUploadData').value == '') {
			alert('Please Browse Image Location');
			document.getElementById('imageUploadData').focus();
			return false;
		}
	}
	
	if(document.getElementById('embed').value == '') {
		alert('Please Enter Embed Video ');
		document.getElementById('embed').focus();
		return false;
	}
}

function CheckChannel() {
	var channel = document.getElementById('channel');
	if(channel.options[channel.selectedIndex].value == 'new') {
		document.getElementById('new_channel').show();
		document.getElementById('not_new_channel').style.display = 'none';
	} else {
		document.getElementById('new_channel').style.display = 'none';
		document.getElementById('not_new_channel').show();
	}
}

function ShowHTMLBanner() 
{
	document.getElementById('secondBanner').style.display = '';
}

function CheckImage() {
	var image = document.getElementById('img_type');
	if(image.options[image.selectedIndex].value == 'url') {
		document.getElementById('imageUrl').show();
		document.getElementById('imageUpload').style.display = 'none';
	} else {
		document.getElementById('imageUrl').style.display = 'none';
		document.getElementById('imageUpload').show();
	}
}

function Delete(url) {
	var check = confirm("Are You Sure? Click (OK) to Continue");
	if (check == true) {
		window.location=url;
	}
}

function checkDate(nums)
{
	if(document.getElementById('date').value == '' && document.getElementById('vperd').value == '')
	{
		document.forms['myforms'].submit();
	}
	else if(document.getElementById('date').value != '' && document.getElementById('vperd').value == '')
	{ 
		document.getElementById('vperd').style.backgroundColor='tomato';
		new Effect.Shake('vperd'); 
		return false;
	}
	else if(document.getElementById('vperd').value != '' && document.getElementById('date').value == '')
	{
		document.getElementById('date').style.backgroundColor='tomato ';
		new Effect.Shake('date'); 
		return false;
		
	}
	else
	{
		
		var error = (cal1.prs_date(document.getElementById('date').value)); 

		if(error) 
		{
			var objRegExp  = /(^-?\d\d*$)/;
			if(!objRegExp.test(document.getElementById('vperd').value) || (document.getElementById('vperd').value) <= 0)
				  	alert('Invalid Number');
			else
				document.forms['myforms'].submit();
			
		}
		
	}
	
	
}

function web_request() {
	  var xmlhttp;

  try {
    xmlhttp = new XMLHttpRequest();
  }
  catch(e) {
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch(e) {
				alert("Your browser doesn't support the HTTP request object");
      }
    }
  }
	
	return xmlhttp;

}