/*
	Azureus Core JavaScript Library
	
	Provides DOM and OOP helper methods and error handling.
	
	Copyright (c) 2006 Azureus, Inc. All rights reserved.
*/

az = {
	version: "1.0.0"
};


// DOM ---------------------------------------------------------------

function element ( /*string*/ id ) {
	return document.getElementById(id);
}

function value ( /*string*/ id ) {
	return element(id).value;
}

function setValue ( /*string*/ id , /*string*/ value ) {
	element(id).value = value;
}


// OOP ---------------------------------------------------------------

function extend ( /*class*/ superClass , /*class*/ subClass ) {
    function inheritance() {}
    inheritance.prototype = superClass.prototype;
    
    subClass.prototype = new inheritance();
    subClass.prototype.constructor = subClass;
    subClass.superCtor = superClass;
    subClass.superClass = superClass.prototype;
}


// ALERT and CONFIRM DIALOGS -----------------------------------------

var msgBoxPreCallback = null;
var msgBoxPostCallback = null;

function setMsgBoxCallbacks ( /*function*/ pre , /*function*/ post ) {
	msgBoxPreCallback = pre;
	msgBoxPostCallback = post;
}

function clearMsgBoxCallbacks ( ) {
	msgBoxPreCallback = null;
	msgBoxPostCallback = null;
}

var alertCallback = null;
function showAlert ( /*string*/ message , /*function*/ callback ) {
	alertCallback = callback;
	handleMessageBox('alert', true, message);
}

function hideAlert ( ) {
	handleMessageBox('alert', false);
}

function btnAlertOk_click ( ) {
	hideAlert();
	if ( alertCallback ) {
		alertCallback.call(null);
	}
}


var confirmCallback = null;
function showConfirm ( /*string*/ message , /*function(boolean)*/ callback ) {
	confirmCallback = callback;
	handleMessageBox('confirm', true, message);
}

function hideConfirm ( ) {
	handleMessageBox('confirm', false);
}

function btnConfirmYes_click ( ) {
	hideConfirm();
	if ( confirmCallback ) {
		confirmCallback.call(null, true);
	}
}

function btnConfirmNo_click ( ) {
	hideConfirm();
	if ( confirmCallback ) {
		confirmCallback.call(null, false);
	}
}


function handleMessageBox ( /*string*/ type , /*boolean*/ show , /*string*/ message ) {
	var boxName = type + '_box';
	var textName = type + '_text';
	
	var boxElem = element(boxName);
	var textElem = element(textName);
	if ( ! boxElem || ! textElem ) {
		// page didn't include the necessary HTML
		if ( show ) {
			if ( type == 'confirm' ) {
				var answer = confirm(message);
				if ( confirmCallback ) {
					confirmCallback.call(null, answer);
				}
			}
			else {
				alert(message);
				if ( alertCallback ) {
					alertCallback.call(null);
				}
			}
		}
		return;
	}
	
	if ( show ) {
		if ( msgBoxPreCallback ) {
			msgBoxPreCallback.call(null);
		}
		
		textElem.innerHTML = message;
		dim(boxElem, true);
	}
	else {
		dim(boxElem, false);
		textElem.innerHTML = "";
		
		if ( msgBoxPostCallback ) {
			msgBoxPostCallback.call(null);
		}
	}
}

function dim ( /*element*/ target , /*boolean*/ show ) {
	var overlayElem = element('overlay');
	if ( ! overlayElem || ! target ) {
		return;
	}
	
	if ( show ) {
		var pageSize = getPageSize();
		overlayElem.style.width = (pageSize[0] + 'px');
		overlayElem.style.height = (pageSize[1] + 'px');
		overlayElem.style.display = 'block';
		var mLeft = (pageSize[0] - $(target.id).getWidth())/2;
		target.style.marginLeft=(mLeft>0?mLeft:0) + 'px'
		target.style.display = 'block';
	}
	else {
		overlayElem.style.display = 'none';
		target.style.display = 'none';
	}
}

//Thanks Lightbox
function getPageSize ( ) {
	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if (yScroll < windowHeight) {
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if (xScroll < windowWidth) {
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}
	
	arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight);
	return arrayPageSize;
}

// ERROR HANDLER -----------------------------------------------------

function displayError ( /*string*/ msg , /*string*/ url , /*int*/ line ) {
//	alert('<b>Error:</b> ' + msg + '<br/><b>URL:</b> ' + url + '<br/><b>Line:</b> ' + line);
	return true; // suppress the default javascript error dialog
}

function setupErrorHandler ( ) {
//	window.onerror = alertError( e );
	window.onerror = displayError;
}

function alertError(e){
	var errMsg='';
	if(e.message){
		errMsg=errMsg+'Message: '+e.message+'\n';
	}

	if(e.description && e.description!=null&&e.description!=''){
		errMsg=errMsg+'Description: '+e.description+'\n';
	}
	if(e.name&&e.name!=null&&e.name!=''){
		errMsg=errMsg+'Name: '+e.name+'\n';
	}
	if(e.fileName&&e.fileName!=null&&e.fileName!=''){
		errMsg=errMsg+'Filename: '+e.fileName+'\n';
	}

	if(e.lineNumber&&e.lineNumber!=null&&e.lineNumber!=''){
		errMsg=errMsg+'Line: '+e.lineNumber+'\n';
	}
	
	alert(errMsg);
}

/*
    logs on the server through an asynchronous javascript http request
    namespace must be less than 40 characters long
    message must be less than 150 characters long
    importance must be one of:
            OPTIONAL USUAL IMPORTANT CRITICAL

    tip: for specific content related logging, include the hash in the message
 */
function log_remote(namespace, message, importance){
    var param = {'message':message, 'importance':importance, 'namespace':namespace};
    var requestParameters = { service : "rpc" ,
                              cmd     : "logging;0;JS;info;" + JSONUtils.toJSONString(param) };

    new Ajax.Request("/app",
					  {
					  	parameters : requestParameters,
					    onSuccess : function(transport){
                            //noop
					    }

                      } );
}

function recommend_rpc(action, hash, azid){
	var param = {'hash':hash }
	if(azid) param = {'hash':hash, 'azid':azid}
	var requestParameters = { 	service : "rpc" ,
            					cmd     : "AZMSG;0;recommend;" + action + ";" + JSONUtils.toJSONString(param) };
	
    new Ajax.Request("/app",
			  {
			  	parameters : requestParameters,
			    onSuccess : function(transport){
                  //noop
			    }

            } );
}

var RemoteTracker = Class.create({
    initialize: function( _type, _action ){
        this.type = _type
        this.action = _action
    },
    track: function( param, args ){
        if( !param ) param = {'message':message, 'importance':importance, 'namespace':namespace};
        this.doTrack(JSONUtils.toJSONString(param), args)
    },
    doTrack: function(jsonParams, args){
        var parameters = args || {}
        parameters.service = "rpc"
        parameters.cmd = "AZMSG;0;"+ this.type +";" + this.action + ";" + jsonParams
        parameters.azid = VUZE.client.getAzId()

        new Ajax.Request("/app",
					  {
					  	parameters : parameters,
					    onSuccess : function(transport){
                            //noop
					    }
                      }
        );
    }
})

var VUZE = window.VUZE || {}
VUZE.client = {
    azid: null,
    getAzId: function(){
        return VUZE.client.azid
    },
    setAzId: function(_azid){
        VUZE.client.azid = _azid
    }
}

// enable error handling
//setupErrorHandler();

/*browser detect*/
var BrowserDetect = {
		init: function () {
			this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
			this.version = this.searchVersion(navigator.userAgent)
				|| this.searchVersion(navigator.appVersion)
				|| "an unknown version";
			this.OS = this.searchString(this.dataOS) || "an unknown OS";
		},
		searchString: function (data) {
			for (var i=0;i<data.length;i++)	{
				var dataString = data[i].string;
				var dataProp = data[i].prop;
				this.versionSearchString = data[i].versionSearch || data[i].identity;
				if (dataString) {
					if (dataString.indexOf(data[i].subString) != -1)
						return data[i].identity;
				}
				else if (dataProp)
					return data[i].identity;
			}
		},
		searchVersion: function (dataString) {
			var index = dataString.indexOf(this.versionSearchString);
			if (index == -1) return;
			return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
		},
		dataBrowser: [
                        {
                                string: navigator.userAgent,
                                subString: "Chrome",
                                identity: "Chrome"
                        },
			{ 	string: navigator.userAgent,
				subString: "OmniWeb",
				versionSearch: "OmniWeb/",
				identity: "OmniWeb"
			},
			{
				string: navigator.vendor,
				subString: "Apple",
				versionSearch: "AppleWebKit",
				identity: "Safari"
			},
			{
				prop: window.opera,
				identity: "Opera"
			},
			{
				string: navigator.vendor,
				subString: "iCab",
				identity: "iCab"
			},
			{
				string: navigator.vendor,
				subString: "KDE",
				identity: "Konqueror"
			},
			{
				string: navigator.userAgent,
				subString: "Firefox",
				identity: "Firefox"
			},
			{
				string: navigator.vendor,
				subString: "Camino",
				identity: "Camino"
			},
			{		// for newer Netscapes (6+)
				string: navigator.userAgent,
				subString: "Netscape",
				identity: "Netscape"
			},
			{
				string: navigator.userAgent,
				subString: "MSIE",
				identity: "Explorer",
				versionSearch: "MSIE"
			},
			{
				string: navigator.userAgent,
				subString: "Gecko",
				identity: "Mozilla",
				versionSearch: "rv"
			},
			{ 		// for older Netscapes (4-)
				string: navigator.userAgent,
				subString: "Mozilla",
				identity: "Netscape",
				versionSearch: "Mozilla"
			}
		],
		dataOS : [
			{
				string: navigator.platform,
				subString: "Win",
				identity: "Windows"
			},
			{
				string: navigator.platform,
				subString: "Mac",
				identity: "Mac"
			},
			{
				string: navigator.platform,
				subString: "Linux",
				identity: "Linux"
			}
		]

	};
	BrowserDetect.init();
	var _browser = BrowserDetect.browser
	var _OS = BrowserDetect.OS
	var _version = BrowserDetect.version
	//alert(_browser + " :: " + _OS)

	function isIE7() {
		return (navigator.userAgent.indexOf("MSIE 7") != -1);
	}
	
	var keyexch = {
		setPublicKey: function(url) {
			new Ajax.Request(url,
				{
					method: "get",
					onSuccess: function(transport) {
						var result = transport.responseText;
						// sendMessage("copy-text", {"text":result});
					},
					onFailure: function() {
						testMessage("RPC request failed");
						// sendMessage("copy-text", {"text":"-1;failed;{}"});
					}
				}
			)
		},
		
		getPassword: function(url) {
			new Ajax.Request(url,
				{
					method: "get",
					onSuccess: function(transport) {
						// alert(transport.status);
						var result = transport.responseText;
						// alert(result);
						testMessage(result);
						// sendMessage("copy-text", {"text":result});
					},
					onFailure: function() {
						testMessage("RPC request failed");
						// sendMessage("copy-text", {"text":"-1;failed;{}"});
					}
				}
			)
		}
	};

/*page dimensions*/
document.page = {
  getDimensions: function(){
	var dimensions = { };
	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;

//	console.log(self.innerWidth);
//	console.log(document.documentElement.clientWidth);

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth;
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}

//	console.log("xScroll " + xScroll)
//	console.log("windowWidth " + windowWidth)

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = xScroll;
	} else {
		pageWidth = windowWidth;
	}
//	console.log("pageWidth " + pageWidth)

	dimensions['width'] = pageWidth;
	dimensions['height'] = pageHeight;
	dimensions['windowWidth'] = windowWidth;
	dimensions['windowHeight'] = windowHeight;

	return new Array(pageWidth,pageHeight,windowWidth,windowHeight);
  },

  getWidth: function() {
    return this.getDimensions()[0];
  },

  getHeight: function() {
    return this.getDimensions()[1];
  }
};

/*
Gradual Transitions
*/
// EaseFromTo (adapted from "Quart.EaseInOut")
Effect.Transitions.EaseFromTo = function(pos) {
    if ((pos/=0.5) < 1) return 0.5*Math.pow(pos,4);
    return -0.5 * ((pos-=2)*Math.pow(pos,3) - 2);
};
// EaseFrom (adapted from "Quart.EaseIn")
Effect.Transitions.EaseFrom = function(pos) {
    return Math.pow(pos,4);
};
// EaseTo (adapted from "Quart.EaseOut")
Effect.Transitions.EaseTo = function(pos) {
    return Math.pow(pos,0.25);
};

/*RPC*/
var VuzeRPC = {
    NAME: {
        DETAILS: "details",
        SCREENSHOTS: "screenshots",
        COMMENTS: "comments"
    },
    send: function(name, params, callbacks){
        var url = "/app"
        var parameters = {
            service: "rpc",
            cmd: "vuze;0;browse;"+name+";"+JSONUtils.toJSONString(params),
            format: "json2"
        }
        new Ajax.Request(url,
        {
            method: "get",
            parameters: parameters,
            onSuccess: function(transport, json){callbacks.success(transport,json)},
            onFailure: callbacks.failure
        })
    }
}