/*****
 *  Copyright 2008 Hoshang Sadiq, Zeryl
 *
 *  JW FLV Media Player v3.14
 *  by Jeroen Wijering - http://www.jeroenwijering.com/
 *
 *  SWFObject v1.5
 *  by Geoff Stearns - http://blog.deconcept.com/swfobject/
 *  2007
 *
 *  For more information on this script, visit:
 *  http://ytexp.zeryl.net/
 *
 *  This file is part of Zeryl YouTube Proxy Browser (Z.Y.P.B.).
 *
 *  Z.Y.P.B. is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Z.Y.P.B. is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Z.Y.P.B.  If not, see <http://www.gnu.org/licenses/>.
 *******/

// Delete text is added to every input field that is made by pressing Add field etc..
// Can be anything, Delete, X even an image
var DeleteText = '<img src="images/close.gif" border="0">';

// Maximum that is allowed for one time getting the video links,
// beware.. there is no unlimited function yet..
// And don't make it to many such as 9999 as it may crash the users pc
var MaxFields = 5;

// This is the time that makes the the help layer disappear
// if the mouse is not focused on the help layer
var DisappearDelay = 1000;

// Don't Edit anything else after this..
// Some general variables that are needed in the script..
var i, esInputs, sLinks, eInput, sCurrValue, eOutputDiv, aActiveXTypes, Http, lastKey, mouseX, mouseY;
var TotalFields = 1;
var ie4 = document.all;
var ns6 = document.getElementById && !document.all;

// to make the shortcuts work
document.onkeydown = getKey;

// three small prototype function for arrays
Array.prototype.InArray = function(sSearch) {
	for (var i in this)
	{
		if (this[i] == sSearch)
		{
			return true;
			break;
		}
	}
	return false;
}

Array.prototype.Add = function(sAdd) {
	this[this.length] = sAdd;
}

String.prototype.stripPixel = function() {
    nStripLength = this.length-2;
    sInputLengt = this.length;
    sOutput = (this.substring(nStripLength, sInputLengt) == 'px') ? this.substring(0, nStripLength) : this;
    return parseInt(sOutput);
}

// Begin a XMLHTTP object. (first time M$ has done something good :-P)
// This is found on the net
function create_http_object() {
	aActiveXTypes = [
		"Microsoft.XMLHTTP",
		"MSXML2.XMLHTTP.5.0",
		"MSXML2.XMLHTTP.4.0",
		"MSXML2.XMLHTTP.3.0",
		"MSXML2.XMLHTTP"
	];

	for(i=0;i<aActiveXTypes.length;i++) {
		try {
			return new ActiveXObject(aActiveXTypes[i]);
		}
		catch(e) {}
	}

	try {
		return new XMLHttpRequest();
	}
	catch(e) {}

	return false;
}

// Get the video(s) that have been entered using Ajax if possible
// If not, just submit the form normally
function GetVideo() {
	Http = create_http_object();
	eOutputDiv = ref('outputdiv');
	eOutputDiv.style.display = '';

	if(!Http) {
		ref('FormPost').onsubmit = '';
		ref('FormPost').onreset = '';
		ref('FormPost').submit();
		return false;
	}
	Http.onreadystatechange = function() {
		if(Http.readyState == 4) {
			if(Http.status == 200) {
				eOutputDiv.innerHTML = Http.responseText;
			} else {
				alert('Error! ('+Http.status+')');
			}
		}
	}

	if(!checkFields()) {
		return false;
	}

	esInputs = document.getElementsByTagName('input');

	var sLinks = '';
	for (var i in esInputs) {
		eInput = esInputs[i];

		if (String(eInput.name).toLowerCase().match('links')) {
			sCurrValue = eInput.value.replace(';', '');
			sCurrValue = sCurrValue.replace(' ', '');
			if(sCurrValue != '') {
				sLinks += (sLinks == '') ? sCurrValue : ';'+sCurrValue;
			}
		}
	}
	
	if(sLinks == '') {
		alert('You need at least 1 video to download');
		return false;
	}

	eOutputDiv.innerHTML = '<img src="images/loading.gif"> Your link(s) are loading!';

	Http.open('POST', 'ytdl.php', true);
	Http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	Http.send('array='+sLinks);
}

// get the right object using the right function
function ref(sObject) {
	if (document.getElementById) {
		return document.getElementById(sObject);
	} else if (document.all) {
		return eval('document.all.' + sObject);
	}
	return false;
}

function checkFields() {
	var DownloadedArray = new Array();
	
	for(var i=1; i<=MaxFields; i++)
	{
		var CurrentField = 'links'+i;
		if(ref(CurrentField)) {
			if(ref(CurrentField).value != '' && !DownloadedArray.InArray(ref(CurrentField).value)) {
				DownloadedArray.Add(ref(CurrentField).value);
			} else {
				if(DownloadedArray.InArray(ref(CurrentField).value)) {
					return 'double_entry';
				} else if (ref(CurrentField).value == '') {
					return 'empty_value';
				}
			}
		} else if(ref(CurrentField) && ref(CurrentField).value == '') {
			return 'empty_value';
		}
	}
	return 'fine';
}

// Add an extra field to the form.
function add_field() {
	// Basically this function creates the following and writes them to the body
	//
	// <input type="text" id="links1" name="links[]" style="width: 500px;" class="input" />
	// <span>&nbsp;</span>
	// <a href="javascript:void(0)">Delete</a>
	// <br />
	//

	var vcheckfield = checkFields();
	if(vcheckfield != 'fine' || TotalFields >= MaxFields) {
		if(vcheckfield == 'double_entry') {
			alert('No double entries please');
		} else if(vcheckfield == 'empty_value') {
			alert('Please fill all fields before continuing');
		} else if(TotalFields >= MaxFields) {
			alert('You have reached your maximum number files per request!');
		}
		return false;
	}

	var eBody, eInput, eSpan, eBr, eAnchor;
	// First select the right tag. which is the first div in the html page
	eBody = ref('ValuesCode');

	// Now begin to create everything
	// Input element for the link
	eInput = document.createElement("input");
	eInput.setAttribute('type','text');
	eInput.setAttribute('name','links[]');
	eInput.setAttribute('id','links'+(TotalFields+1));
	eInput.setAttribute('size','100');
	eInput.setAttribute('class','input');
	eInput.style.width = '500px';

	// we need an empty space, use the span tag
	eSpan = document.createElement("span");
	eSpan.id = 'DelSpan'+(TotalFields+1);
	eSpan.innerHTML = '&nbsp;';
	
	// a new line, br
	eBr = document.createElement("br");
	eBr.id = 'DelBr'+(TotalFields+1);

	// And the preparation for the anchor tag to delete that field
	eAnchor = document.createElement("a");
	eAnchor.setAttribute('href','javascript:void(0)');
	eAnchor.id = 'DelAnchor'+(TotalFields+1);
	// to change this, there is a variable in the top
	eAnchor.innerHTML = DeleteText;

	// onclick is a function to delete the tags we just made in this function
	// and subtract 1 from the TotalFields..
	eAnchor.onclick = function() {
		eBody.removeChild(eInput);
		eBody.removeChild(eSpan);
		eBody.removeChild(eAnchor);
		eBody.removeChild(eBr);
		ref('helpLayer').style.top = (ref('helpLayer').style.top.stripPixel()-23)+'px';
		TotalFields--;
		return false;
	}

	ref('helpLayer').style.top = (ref('helpLayer').style.top.stripPixel()+23)+'px';
	// now write everything
	eBody.appendChild(eInput);
	eBody.appendChild(eSpan);
	eBody.appendChild(eAnchor);
	eBody.appendChild(eBr);
	// Then add one to TotalFields
	TotalFields++;
}

function resetPage(e) {
	ref('outputdiv').innerHTML = '';
	ref('ValuesCode').innerHTML = '';
	ref('links1').value = '';
	hidemenu(e);
}

function DelLastInput() {
	if(TotalFields <= 1) {
		return;
	}
	
	sInput = 'links'+TotalFields;
	sSpan = 'DelSpan'+TotalFields;
	sBr = 'DelBr'+TotalFields;
	sAnchor = 'DelAnchor'+TotalFields;

	eBody = ref('ValuesCode');
	eBody.removeChild(ref(sInput));
	eBody.removeChild(ref(sSpan));
	eBody.removeChild(ref(sBr));
	eBody.removeChild(ref(sAnchor));
	ref('helpLayer').style.top = (ref('helpLayer').style.top.stripPixel()-23)+'px';
	TotalFields--;
}

function getKey(e) {
	if (e == null) { // ie
		keycode = '';
	} else { // mozilla
		keycode = e.which;
	}
	
	if(lastKey == '18') // key ALT
	{
		if(keycode == '83') { // submit, key s for submit
			GetVideo();
			return false;
		}
		else if(keycode == '82') { // reset, key r for reset
			resetPage(e);
			return false;
		}
		else if(keycode == '65') { // add, key a for add
			add_field();
			return false;
		}
		else if(keycode == '72') { // add, key h for help
			openHelp(true);
			return false;
		}
		else if(keycode == '67') { // add, key c for close
			closeHelp();
			return false;
		}
		else if(keycode == '68') { // add, key d for delete
			DelLastInput();
			return false;
		}
	}
	lastKey = keycode;
}

function openHelp(shortkey_pressed) {
	shortkey_pressed = (!shortkey_pressed) ? false : shortkey_pressed;
	ref('fieldsLimit').innerHTML = MaxFields;
	if(shortkey_pressed) {
		ref('helpLayer').style.display = '';
		delayhidemenu();
		clearhidemenu();
	}
}

function closeHelp() {
	ref('helpLayer').style.display = 'none';
	delayhidemenu();
	clearhidemenu();
}

function getposOffset(what, offsettype) {
	var totaloffset = (offsettype == "left") ? what.offsetLeft : what.offsetTop;
	var parentEl = what.offsetParent;
	while (parentEl != null) {
		totaloffset = (offsettype == "left") ? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
		parentEl = parentEl.offsetParent;
	}
	return totaloffset;
}


function showhide(obj, e) {
	if (ie4 || ns6) {
		dropdownlayer.style.left = "-500px";
		dropdownlayer.style.top = "-500px";
	}
	dropdownlayer.style.width = '450px';
	obj.display = (e.type == "click" && obj.display == "none" || e.type == "mouseover") ? '' : ((e.type == "click") ? 'none' : obj.display);
	delayhidemenu();
	clearhidemenu();
}

function iecompattest() {
	return (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
}

function clearbrowseredge(obj, whichedge) {
	var edgeoffset=0
	if (whichedge == "rightedge") {
		var windowedge = ((ie4 && !window.opera) ? iecompattest().scrollLeft + iecompattest().clientWidth : window.pageXOffset + window.innerWidth) - 15;
		dropdownlayer.contentmeasure = dropdownlayer.offsetWidth;
		if (windowedge-dropdownlayer.x < dropdownlayer.contentmeasure) {
			edgeoffset = dropdownlayer.contentmeasure-obj.offsetWidth;
		}
	} else {
		var topedge = (ie4 && !window.opera) ? iecompattest().scrollTop : window.pageYOffset;
		var windowedge = (ie4 && !window.opera) ? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18;
		dropdownlayer.contentmeasure = dropdownlayer.offsetHeight;
		if (windowedge-dropdownlayer.y < dropdownlayer.contentmeasure) { // move up?
			edgeoffset = dropdownlayer.contentmeasure+obj.offsetHeight;
			if ((dropdownlayer.y-topedge) < dropdownlayer.contentmeasure) { // up no good either?
				edgeoffset = dropdownlayer.y + obj.offsetHeight - topedge;
			}
		}
	}
	return edgeoffset
}

function dropdownmenu(layer, obj, e) {
	if (window.event) {
		event.cancelBubble = true;
	} else if (e.stopPropagation) {
		e.stopPropagation()
	}
	clearhidemenu();
	dropdownlayer = ref(layer);

	if (ie4 || ns6) {
		showhide(dropdownlayer.style, e);
		dropdownlayer.x = getposOffset(obj, "left");
		dropdownlayer.y = getposOffset(obj, "top");
		dropdownlayer.style.left = dropdownlayer.x-clearbrowseredge(obj, "rightedge")+"px";
		dropdownlayer.style.top = dropdownlayer.y-clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+"px";
	}

	return (ie4 || ns6) ? false : true;
}

function contains_ns6(a, b) {
	while (b.parentNode) {
		if ((b = b.parentNode) == a) {
			return true;
		}
	}
	return false;
}

function dynamichide(e) {
	if (ie4 && !dropdownlayer.contains(e.toElement)) {
		delayhidemenu();
	} else if (ns6 && e.currentTarget != e.relatedTarget && !contains_ns6(e.currentTarget, e.relatedTarget)) {
		delayhidemenu();
	}
}

function hidemenu(e) {
	if (typeof dropdownlayer != "undefined") {
		if (ie4 || ns6) {
			dropdownlayer.style.display = "none";
		}
	}
}

function delayhidemenu() {
	if (ie4 || ns6) {
		delayhide = setTimeout("hidemenu()", DisappearDelay);
	}
}

function clearhidemenu() {
	if (typeof delayhide != "undefined") {
		clearTimeout(delayhide);
	}
}

