/******************************************************************
*	file		:		clientscript/global.js
*
*	General methods
*
******************************************************************/

/*
*	Get an object by it's ID
*/
function _(idname)
{
	if( document.getElementById )
	{
		return document.getElementById(idname);
	}
	else if( document.all )
	{
		return document.all[idname];
	}
	else
	{
		return false;
	}
}

getElement=_;

/*   Get an object by its className */
function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}

/*
*	Fetch tags by tagname from parent object.
*/
function fetch_tags(parent, tagname)
{
	if( parent == null )
	{
		return false;
	}
	else if( typeof parent.getElementsByTagName != 'undefined' )
	{
		return parent.getElementsByTagName(tagname);
	}
	else if( parent.all && parent.all.tags )
	{
		return parent.all.tags(tagname);
	}
	else
	{
		return new Array();
	}
}

/*
*	Stops event bubbling
*/
function do_event(e)
{
	if( !e )
		var e = window.event;
		
	e.cancelBubble = true;
	
	if( e.stopPropagation )
		e.stopPropagation();
	
	return e;
}

/*
*	Returns bottom left position of an object
*/
function findPos(obj)
{
	var curleft = curtop = 0;
	var height = obj.offsetHeight;
	
	if (obj.offsetParent)
	{
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent)
		{
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
		
		curtop += height;
	}
	return [curleft,curtop];
}

/*
*	Returns an object's dimensions
*/
function objectDim( obj )
{
	objw = 0;
	objh = 0;
	
	if( obj.style.width )
		objw = obj.style.width.replace(/px/,'');
	else if( obj.offsetWidth )
		objw = obj.offsetWidth;
	
	if( obj.style.height )
		objh = obj.style.height.replace(/px/,'');
	else if( obj.offsetHeight )
		objh = obj.offsetHeight;	
	
	return [ objw, objh ];
}

/*
*	Returns document dimension
*/
function documentDim()
{
	var dimX = 0
	var dimY = 0;
	
	if( typeof( window.innerWidth ) == 'number' )
	{
		//Non-IE
		dimX = window.innerWidth;
		dimY = window.innerHeight;
	}
	else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
	{
		//IE 6+ in 'standards compliant mode'
		dimX = document.documentElement.clientWidth;
		dimY = document.documentElement.clientHeight;
	}
	else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
	{
		//IE 4 compatible
		dimX = document.body.clientWidth;
		dimY = document.body.clientHeight;
	}
	
	return [ dimX, dimY ];
}


/*
*	Returns cursor position
*/
function cursorPos(e)
{
	if(!e) e = window.event;
	
	xpos = 0;
	ypos = 0;
	
	if ( e.pageX && e.pageY )
	{
		xpos = e.pageX;
		ypos = e.pageY;
	}
	else if( e.clientX && e.clientY )
	{
		xpos = e.clientX + ( document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft );
		ypos = e.clientY + ( document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop );
	}

	return [ xpos, ypos ];	
}

/*
*	Stripes table-rows
*/
function stripe(id)
{
	var even = false;
	var table = document.getElementById(id);
	if (! table) { return; }
	var tbodies = table.getElementsByTagName("tbody");
	
	for (var h = 0; h < tbodies.length; h++)
	{
		var trs = tbodies[h].getElementsByTagName("tr");

  	   for (var i = 0; i < trs.length; i++)
  	   {
			var tds = trs[i].getElementsByTagName("td");
			for (var j = 0; j < tds.length; j++)
			{
				var mytd = tds[j];
				if( hasClass(mytd) )
					mytd.className = mytd.className + ' ' + (even ? 'even' : 'odd');
				else
					mytd.className = even ? 'even' : 'odd';
			}
			even =  ! even;
		}
	}
}

function hasClass(obj)
{
	var result = false;
	if (obj.getAttributeNode("class") != null)
	{
		result = obj.getAttributeNode("class").value;
	}
	return result;
}


/*
*	Validates a form, fields are given as arguments
*/
function validateForm( formname )
{
	var a = arguments;
	
	for( i=1; i < a.length; i++ )
	{
		if( formname.elements[a[i]].value == "" )
		{
			alert( "Fyll i alla fält!" );
			formname.elements[a[i]].focus();
			return false;
		}
	}

	return true;
}

/*
*	Removes all childnodes from a given node
*/
function removeChildren(holder) {
	while(holder.hasChildNodes()){
		holder.removeChild(holder.lastChild);
	}
}


/*
*	Resizes an image after load
*/
function img_resize(image,neww)
{
	w = image.width;
	if( w > neww )
		image.width = neww;
}


function make_ajax_clean(in_string)
{
	in_string=in_string.toString();
	return encodeURIComponent(in_string.replace(/€/gi,'&#8364;'));
}


function tabs(tabbar_el_id)
{
	var that=this;
	this.tab_list=new Array();
	this.current=false;
	this.tab_class='tab_item';
	this.selected_class='tab_item selected';

	this.tabbar_el=getElement(tabbar_el_id);
	if(!this.tabbar_el) return false;
	
	this.tab=function(tab_element,target_element)
	{
		var tabbar=that;
		var this_tab=this;
		this.tab_element=tab_element;
		this.target_element=target_element;
		if(!this.tab_element)
		{
			return false;
		}
		if(target_element!=false)
		{
			this.target_element.style.display="none";
		}
		
		if(typeof this.tab_element.onclick !="undefined")
		{
			var old_on_click=this.tab_element.onclick;
		}
		else var old_on_click=function(){}
		
		this.tab_element.setAttribute('href','#');
		this.tab_element.setAttribute('onclick','return false;');
		this.activate=function()
		{
			if(tabbar.current!=false)
			{
				tabbar.current.tab_element.className=tabbar.tab_class;
				if(tabbar.current.target_element!=false)
				{
					tabbar.current.target_element.style.display='none';
				}
			}
			this.tab_element.className=tabbar.selected_class;
			if(this.target_element!=false)
			{
				this.target_element.style.display="block";
			}
			tabbar.current=this;
		}
		
		this.tab_element.onclick=function(e)
		{
			e=e || window.event;
			this_tab.activate();
			
			return false;
		}

	}
	
	var start_index=0;
	for(var i=0;i<this.tabbar_el.childNodes.length;i++)
	{
		var cur_child=this.tabbar_el.childNodes[i];

		if(cur_child.className==this.tab_class) 
		{
			var target_element_id=cur_child.getAttribute('href',2);
			var tab_name=cur_child.getAttribute('name');
			if(tab_name!== null && tab_name=='start')
			{
				start_index=this.tab_list.length;
			}
			
			if(!target_element_id || target_element_id=="#false")
			{
				var target_el=false;
			}
			else
			{
				target_element_id=target_element_id.replace(/^#/,'');
				var target_el=getElement(target_element_id);
				if(typeof target_el == 'undefined')
				{
					target_el=false;
				}
			}
			
			var new_tab=new this.tab(cur_child,target_el);//create a tab
			this.tab_list.push(new_tab);
		}
	
	}
	if(this.tab_list.length>0)
	{
		this.tab_list[start_index].activate();
	}

}//end of tabs

var request_success=function(response)
{
	response=response.toString();
	var code=response.match(/^[a-z]+;/i);
	if(code==null) return false;
	var returnval=new Object();
	returnval.response=response.replace(/^[a-z]+;/i,'');
	code=code[0].split(';').join('');
	switch(code)
	{
		case 'true': 
			returnval.code=true;
		break;
		case 'false':
			returnval.code=false;
		break;
		default:
			returnval.code=code[0];
		break;
	}//end of switch
	

	return returnval;
}

var ajaxObj=function()
{/***Creates and returns an ajax object ***/
	var obj;
	if(window.XMLHttpRequest)
	{
		obj = new XMLHttpRequest();
	}
	else//IE6
	{
		obj = new ActiveXObject("Microsoft.XMLHTTP");
	
	}
	
	return obj;
}

var make_ajax_request=function(object)
{
	
	if(!object.url) return false;//return false if no url is defined
	if(!object.data)
	{
		object.data={}
	}
	else
	{
		
		for(var key in object.data)
		{
			object.data[key]=object.data[key].toString().replace(/€/gi,'&#8364;');
		}
	}

	var async=false;
	if(!object.sync)
	{
		async=true;
	}

	var return_type='json';
	if(!object.json)
	{
		return_type='html';
	}
	//set request-type
	var request_type='POST';
	if(!object.post)
	{
		request_type='GET';
	}
	/***********************************************************/
	/***if no callback defined, user our own callback
	/***********************************************************/
	if(!object.callback)
	{

		return jQuery.ajax({
			url:object.url,
			data:object.data,
			type:request_type,
			async:async,
			dataType:return_type,
			success:function(response)
			{
				if(object.error_message!==false)//error-reporting can be turned off with object.error_message=false
				{
					var error=request_success(response);
					if(error!==false)
					{
						alert(error.response);//else alert out the error-message
					}//endif
				}//endif
			},
			cache:false,
			error:function()
			{
				alert('connection error!')
			}
		});//end of ajax-request
		
	}//endif
	/***********************************************************/
	/***if a callback is defined
	/***********************************************************/
	else//if a callback is defined
	{
	
		return jQuery.ajax({
			url:object.url,
			data:object.data,
			type:request_type,
			async:async,
			dataType:return_type,
			success:function(response)
			{
				var error=false;
				if(object.error_message!==false)//error-reporting can be turned off with object.error_message=false
				{
					error=request_success(response);
					if(error!==false)
					{
						alert(error.response);//else alert out the error-message
						if(object.halt_on_error!==false && error.code==false) return false;
					}//endif
				}//endif
				object.callback(response,error);//call the callback
			},
			cache:false,
			error:function()
			{
				alert('connection error!')
			}
		});//end of ajax-request
		
	}
}//end of function


var unescapeHTML = function(html)
{
	return html.split("&amp;").join("&").split("&lt;").join("<").split("&gt;").join(">");
}

/*

var toggle_visible=function(id)
{
	var element=document.getElementById(id);
	if(element.style.visibility=='visible')
	{
		element.style.visibility='hidden';
		element.style.display='none';
		return 0;
	}
	element.style.visibility='visible';
	element.style.display='block';
}
*/
/**********************************************************************************************
*
*	Toggle visibility of an object
*
**********************************************************************************************/
var toggle_visible = function(id)
{

	var element=document.getElementById(id);
	if(!element) return false;
	
	if(element.style.visibility=='visible')
	{
		if(typeof jQuery == "undefined")
		{
			element.style.visibility='hidden';
			element.style.display='none';
		}
		else
		{
			jQuery(element).hide(100,function()
			{
				element.style.visibility='hidden';
				element.style.display='none';
			});
		}
		
		return false;
	}
	
	if(typeof jQuery == "undefined")
	{
		element.style.visibility='visible';
		element.style.display='block';
	}
	else
	{
		jQuery(element).show(100,function()
		{
			element.style.visibility='visible';
			element.style.display='block';
		});
	}
	
	return false;
}


var remove_element = function(element)
{
	element.parentNode.removeChild(element);
}
/************************************************************/
/***Canvas and scroll info functions
/************************************************************/
var getCanvasWidth=function()
{
	de=document.documentElement;
	if(!de)
	{
		de=Object();
		de.clientWidth=false;
	}
	return window.innerWidth || self.innerWidth || de.clientWidth || document.body.clientWidth;
}
	/*******************************************************************************/

var getCanvasHeight = function()
{
	de=document.documentElement;
	if(!de)
	{
		de=Object();
		de.clientHeight=false;
	}
	return window.innerHeight || self.innerHeight || de.clientHeight || document.body.clientHeight;
}

	/*******************************************************************************/

var getScrollHeight = function()
{
	de=document.documentElement;
	if(!de)
	{
		de=Object();
		de.scrollTop=false;
	}

	if(!de.scrollTop && !document.body.scrollTop && !window.pageYOffset) return false;
	return de.scrollTop || document.body.scrollTop || window.pageYOffset;
}
	/*******************************************************************************/

var getScrollWidth=function()
{
	de=document.documentElement;
	if(!de)
	{
		de=Object();
		de.scrollLeft=false;
	}
	if(!de.scrollLeft && !document.body.scrollLeft && !window.pageXOffset) 
	{
		return false;
	}
	return de.scrollLeft || document.body.scrollLeft || window.pageXOffset;
}

/***************************************************************************************
*	Function for outputting messages to firbug console
*
*	@param message	Can be string, object, array
*	@param mode		if "console" the firebug console is used, else the
*						message is put in a div at the page bottom
*
*/	
function debug( message, mode )
{
	if( !mode )
	{
		mode = 'console';
	}
	
	if(typeof console == 'object')
	{
		console.info(message);
	}
}




/***************************************************************************************
*	Get an element by its id
*
*	@param idname	ID of the tag to fetch
*
*	@return object
*/
function getbyid( idname )
{
	if( typeof(idname) == 'object' )
	{
		return idname;
	}
	
	if( document.getElementById )
	{
		return document.getElementById(idname);
	}
	else if( document.all )
	{
		return document.all[idname];
	}
	else
	{
		return false;
	}
}

/***************************************************************************************
*	Fetch tags by tagname from parent-object
*
*	@param parent		Parent object in which to search for tags
*	@param tagname		Type of tags to fetch
*
*	@return array
*/
function fetchtags( parent, tagname )
{
	if( parent == null )
	{
		return false;
	}
	else if( typeof parent.getElementsByTagName != 'undefined' )
	{
		return parent.getElementsByTagName(tagname);
	}
	else if( parent.all && parent.all.tags )
	{
		return parent.all.tags(tagname);
	}
	else
	{
		return new Array();
	}
}

/*
* ##########################################################################################################################################
* #
* #	Ajax handler
* #
* ##########################################################################################################################################
*/
/****************************************************************************************
*	Method for sending ajax post requests and handle JSON-data
*
*	@param json	Is the response JSON-encoded?
*/
function ajax_handler(json, async)
{
	this.response = '';
	this.containerobj = false;
	this.requestobject = false;
	// json (true) the data is returned in json_encode() format
	this.json = ( json ? true : false );
	// asynchronous (true) the server returns the request when it is
	// finished without stalling the script
	// synchronous (false) the script stalls and waits for the request to finish
	this.async = ( async ? true : false );
	
	
	/****************************************************************************************
	*	Initialize the request object
	*/
	this.init = function()
	{
		if( window.XMLHttpRequest )
		{
			this.requestobject = new XMLHttpRequest();
		}
		else
		{
			this.requestobject = new ActiveXObject("Microsoft.XMLHTTP");
		}
		
		this.requestobject.onreadystatechange = this.rs;
		return ( this.requestobject ? true : false );
	};
	
	/****************************************************************************************
	*	Perform a normal POST-request and return
	*	the response
	*
	*	@param url	Url of the file
	*	@param url	POST Parameters
	*
	*/
	this.post = function( url, data )
	{
		if( this.requestobject )
		{
			data = ( data ? data : '' );
			
			this.requestobject.open('post', url, this.async);
			this.requestobject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			this.requestobject.send(data);
			
			if( this.json )
			{
				if( this.requestobject.responseText != '' )
				{
					this.response = eval('(' + this.requestobject.responseText + ')');
				}
				else
				{
					this.response = '';
				}
			}
			else
			{
				this.response = this.requestobject.responseText;
			}
		
			return this.response;
		}
		
		return false;
	};
	
	
	/****************************************************************************************
	*	Perform a normal GET-request and return
	*	the response
	*
	*	@param url	Url of the file
	*
	*/
	this.get = function( url )
	{
		if( this.requestobject )
		{
			this.requestobject.open('get', url, this.async);
			this.requestobject.send(null);
		}
		
		return false;
	};
	
	/****************************************************************************************
	*	Readystate change wrapper for asynchronous mode, this
	*	can be overwritten when creating a new instance of the class
	*
	*/
	this.rs = function()
	{
		if( this.requestobject.readyState == 4 )
		{
			if( this.json )
			{
				this.response = eval('(' + this.requestobject.responseText + ')');
			}
			else
			{
				this.response = this.requestobject.responseText;
			}
		}
	};
	
	// Initialize
	this.init();
}


/*
* ##########################################################################################################################################
* #
* #	File uploader
* #
* ##########################################################################################################################################
*/
var fileuploaders = new Array();

function init_fileuploader( uploadid, convert )
{
	fileuploader[uploadid] = null;
	fileuploader[uploadid] = new fileuploader(uploadid, convert);
}

/****************************************************************************************
*	File uploader
*
*	@param string uploadid	ID of the upload, used by APC
*	@param bool convert		When the upload finishes, start polling ffmpeg status		
*
*/
function fileuploader( uploadid, convert )
{
	this.uploadid = uploadid;
	this.convert = convert;
	
	this.uploadframe = 	getbyid('uploaderframe_'+this.uploadid);
	this.uploadform = 	getbyid('uploaderform_'+this.uploadid);
	this.videoform = 		getbyid('videoform_'+this.uploadid);
	this.uploadstatus = 	getbyid('uploadstatus_'+this.uploadid);
	this.uploadbutton = 	getbyid('uploadbutton_'+this.uploadid);
	this.conversionstatus = getbyid('conversionstatus_'+this.uploadid);
	
	this.filename = 		getbyid('filename_'+this.uploadid);
	this.percentage = 	getbyid('percentage_'+this.uploadid);
	this.timeleft = 		getbyid('timeleft_'+this.uploadid);
	this.speed = 			getbyid('speed_'+this.uploadid);
	
	this.progressbar = 	getbyid('progressbar_'+this.uploadid);
	this.cprogressbar_container = 	getbyid('cprogressbar_container_'+this.uploadid);
	this.cprogressbar = 	getbyid('cprogressbar_'+this.uploadid);
	
	this.timer = null;
	
	/****************************************************************************************
	*	Initialize the file uploader	
	*
	*/
	this.init = function()
	{
		// Set button properties
		var that = this;
		this.uploadbutton.uploadid = this.uploadid;
		this.uploadbutton.onclick = that.startupload;
	};

	/****************************************************************************************
	*	Start the actual upload	
	*
	*/
	this.startupload = function()
	{
		var obj = fileuploader[this.uploadid];

		// Hide the upload form and display the status
		// with progressbar etc
		obj.videoform.style.display = 'none';
		obj.uploadstatus.style.display = 'block';
		obj.progressbar.style.width = '0%';
		if( obj.convert )
		{
			obj.cprogressbar.style.width = '0%';
		}
		obj.updateprogress(obj);
		obj.timer = setInterval(function(){obj.updateprogress(obj);}, 1000);
	};
	
	/****************************************************************************************
	*	Update the upload progressbar	
	*
	*/
	this.updateprogress = function(obj)
	{
		var a = new ajax_handler(true);
		var data = a.post('ajax.upload.php?do=uploadprogress',
		'uploadid='+obj.uploadid
		);
		
		if( data.success )
		{
			if( data.done )
			{
				obj.uploadstatus.style.display = 'none';
				clearInterval(obj.timer);
				
				if( obj.convert )
				{
					obj.conversionstatus.style.display = 'block';
					obj.conversionprogress(obj);
					obj.timer = setInterval(function(){obj.conversionprogress(obj);}, 1000);
				}
			}
			else
			{
				obj.progressbar.style.width = data.percentage + '%';
				obj.filename.innerHTML = data.filename;
				obj.percentage.innerHTML = data.percentage + '%';
				obj.timeleft.innerHTML = data.timeleft;
				obj.speed.innerHTML = data.transferred + ' @ ' + data.speed;
			} 
		}
	};
	
	/****************************************************************************************
	*	Update the conversion progress bar	
	*
	*/
	this.conversionprogress = function(obj)
	{
		var a = new ajax_handler(true);
		var data = a.post('ajax.upload.php?do=conversionprogress',
		'uploadid='+obj.uploadid
		);
				
		if( data.success )
		{
			if( data.done )
			{
				obj.cprogressbar_container.style.display = 'none';
				clearInterval(obj.timer);
			}
			else
			{
				obj.cprogressbar.style.width = data.percentage + '%';
			} 
		}
	
	};
	
	/****************************************************************************************
	*	Initialize
	*
	*/
	this.init();
}
