var JUNO_API =
{
	// Vars
	config:
	{
		new_window_name		:	'JunoRecords',
		player_id			:	'junoplayer',
		url_base			:	window.location.protocol + '//' + window.location.hostname,
		surl_base_api		:	'https' + '://' + window.location.hostname + '/api/?',
		url_base_api		:	'http' + '://' + window.location.hostname + '/api/?',
		data_vars			:	{},
		loginCookies 		:	 ['ajaxLogin','ajaxLoginCancel','ajaxLoginRegister','ajaxLoginResendPassword','ajaxLoginResendPasswordRequest','ajaxCreateAccount'],
		window			:		{
									'height' 	:	145,
									'width' 	: 	250,
									'toolbar'	:	0,
									'scrollbar' :   0,
									'resizable'	:	0,
									'location'	:	0,
									'type'		:  'text/html',
									'active_name' : ''	
								}
	},
	
	// Objects and friends
	User:
	{
		doCheckLogged	:	function()
		{
			var logged = $.ajax({url: JUNO_API.config.url_base_api + 'method=user.doCheckLogged', async: false}).responseText;
			return ( logged*1==1 );
		},
		
		doIfLogged	:	function(ok_callback, error_callback)
		{
			var entry;
			
			if(arguments.length == 2)
			{
				callback = {ok: ok_callback, error: error_callback};
			}
			else if(arguments.length == 1)
			{
				callback = ok_callback;
			}
			$.ajax({
				url : JUNO_API.config.url_base_api + 'method=user.doCheckLogged',
				type : 'GET',
				dataType : 'text',
				timeout : 1000,
				error : function(data){
					if(typeof(callback) == 'object')
						{
							eval(callback.error);
						} 
					},
				success : function(data){
						if(typeof(callback) == 'object')
						{
							eval(callback.ok);
						}
						else
							eval(callback);
					}
			});
			/*
			$.get(
				JUNO_API.config.url_base_api + 'method=user.doCheckLogged',
				{}, 
				function(data)
				{
					if(data == 1)
					{
						if(typeof(callback) == 'object')
						{
							eval(callback.ok);
						}
						else
							eval(callback);
					}
					else
					{
						if(typeof(callback) == 'object')
						{
							eval(callback.error);
						} 
					}
				}  
			); */
			
		},
		
		doLoginAndRedir	:	function(redir_url)
		{
			url = JUNO_API.User.getLoginURL() + '?redir=' + escape(redir_url);
			JUNO_API.Window.open({'url': url});
		},
		
		getLoginURL	:	function()
		{
			return ('https://' + window.location.hostname + '/login/');
		},
		getPage:	function(page, div, _complete)
		{
			//cross domain || protocol work around... and here arrives the cookie
			document.domain = document. location.hostname.match(/\.(\w+\.[^\.]+)$/)[1];
			
			$.ajax({
					type:    'GET',
					url: 	 JUNO_API.config.url_base_api + 'method=user.getPage&output_type=html',
					data:    'page=' + page,
					dataType:'html',
					error:   function(XHR, textStatus, errorThrown) { return false; },
					complete: function(){
						if(typeof _complete !== 'undefined'){
							_complete(); // success / complete callback relying on further action from here like registration
						}
					},
					success: function(data) {
							$('#' + div).html(data);
							return true;
						}
				 });
		},
		getFramePage: function(which){
			var is_secure = false;
			try {
				//var src = parent.frames['ajax_login_frame'].location.href;
				var src = parent.frames['ajax_login_frame'].location.href;
			} catch(e) {
				//alert(e);
				//need an opera workaround
			}
			
			if(JUNO_API.User.is_secure_url(src)){
				src = src.replace(JUNO_API.config.surl_base_api, '');
			}else{
				src = src.replace(JUNO_API.config.url_base_api, '');
			}
			
			src = src.split('&');
			
			for(var i in src){
				tmp_src = src[i].split('=')
				if(tmp_src[0] == 'page'){
					tmp_src[1] = which;
					src[i] = tmp_src.join('=');
					
				}else if(tmp_src[0] == 'is_secure'){
					if(tmp_src[1] =='on'){
						is_secure = true;
						
					}
				}
			}
			src = src.join('&');
			
			/*
			 * PLEASE NOTE these are the pages names ... not the function names. Used to dynamically change the
			 * frame protocol to be identical to the parent protocol for security. if they are not identical,
			 * they are treated as cross domain and will fail.
			 */
			if(which == 'register' || which == 'login' || which == 'forgotten_password' || is_secure){
				src = JUNO_API.config.surl_base_api + src;
				
				parent.frames['ajax_login_frame'].location.replace(src)
			}else{
				src = JUNO_API.config.url_base_api + src;
				
				parent.frames['ajax_login_frame'].location.replace(src);
			}
			
		},
		doLogin:		function(form)
		{	
					var ai = '<div id="ajax_login_activity_indicator" style="position: absolute; top: 10%; width: 99%; height: 70%; z-index: 100;"><img style="position:absolute;top:50%;left:30%" src="/images/loading.gif"/></div>';
					$('#login_div').fadeTo('fast',0.3).prepend(ai);
					if(typeof form == 'undefined')
					return false;
					
					$('#' + form + ' :input').each(function(){
						if(this.name.replace(/^\s+|\s+$/g,"")!= ''){
							if(this.checked){
								JUNO_API.config.data_vars[this.name]  = this.checked
							}else if(this.name=='email' || this.name=='password' || this.name == 'password_again'){
								JUNO_API.config.data_vars[this.name]  =  $.base64Encode(this.value);
							}else{
								JUNO_API.config.data_vars[this.name]  = this.value;
							}
							
						}
					})
					
					//open window before ajax to by pass popup blockers
					if(JUNO_API.config.data_vars.callback){
						//JUNO_API.User.openWindow();  will be displayed in a div as parent window cannot be accessed
					}
					
					$.ajax({
							type:    'POST',
							url: 	 JUNO_API.config.surl_base_api,
							data:    JUNO_API.config.data_vars,
							dataType:'html',
							timeout : 20000,
							error:   function(XHR, textStatus, errorThrown) {
								if(textStatus == 'timeout'){
									parent.location.replace('/login/');
									
								}
								return false; 
								},
							complete: function(){$('#login_div').fadeTo('fast',1);$('#ajax_login_activity_indicator').remove()},
							success: function(data) {
									doLoginCallBack(data);
								}
						 });
					
		},
		openWindow: function(options)
		{
			if(typeof options == 'undefined'){
				options = {};
			}
			var h 	= options.height 		|| JUNO_API.config.window.height;
			var w 	= options.width 		|| JUNO_API.config.window.width;
			var tb 	= options.toolbar 		|| JUNO_API.config.window.toolbar;
			var sb 	= options.scrollbars 	|| JUNO_API.config.window.scrollbars;
			var rs 	= options.resizeable 	|| JUNO_API.config.window.resizeable;
			var lcn	= options.location  	|| JUNO_API.config.window.location;
			var nm	= options.name			|| JUNO_API.config.new_window_name;
			var tp 	= options.type			|| JUNO_API.config.window.type;
			
			var new_win = window.open('', nm, 'height=' + h + ',width=' + w + ',toolbar=' + tb + ',scrollbars=' + sb + ',resizable=' + rs + ',location=' + lcn + '');
			new_win.document.open(tp,"replace");
			new_win.document.close();
				
				
			if(parent){
				parent.JUNO_API.config.window['active_name'] = new_win;
			}else{
				JUNO_API.config.window['active_name'] = active_window = new_win;
			}	
				
				
		},
		make_data_vars_for_get : function()
		{
			data_vars_url = ''; 
			for(var i in JUNO_API.config.data_vars){
				if(i.replace(/^\s+|\s+$/g,"") !=""){
					data_vars_url += i + '=' + JUNO_API.config.data_vars[i] + '&';
				}
			}
			return data_vars_url;
		},
		doReloadTopmenu : function()
		{
				$("table#top_menu").hide('slow');
				$.ajax({
							type:    'GET',
							url: 	 JUNO_API.config.url_base_api,
							data:    'method=user.doReloadTopmenu',
							dataType:'html',
							error:   function(XHR, textStatus, errorThrown) { return false; },
							success: function(data) {
								$("table#top_menu").html(data);
								$("table#top_menu").show('slow');	
							}
				});
				
			},
			removeFrame : function(){
				tb_remove();
				 /** backward compatability -- node has to be deleted from dom for ol skool ff 2.0 as it returns an error when this node is recreated
				* cannot access frame properties coz in its warped mind... dom element was removed sad case... too smart for its self
				**/
			  	if($.browser.msie)
					window.frames['ajax_login_frame'].close();
				else
					delete window.frames['ajax_login_frame'];
				
				return false;
			},
			is_secure_url : function(url){
				if(url.substr(0,5) == 'https'){
					return true;
				}
				return false;
			}
	},
	
	Player:
	{
		addToWishlist : function (awPar)
		{
			var str = awPar.replace('wishlist/add/?', '').replace('&popup=yes', '');
			var matches = str.match(/^titleid=(\d+)&productid=(\d+)$/);
			if(matches.length>0) {
				JUNO_API.Wishlist.addProduct(matches[1], matches[2], 'player');
			}
		},
		
		getSWF : function()
		{
			var id = JUNO_API.config.player_id;
			if(document.getElementById) {
				return document.getElementById(id);
			} else {
				return window[id];
			}
		}
	},
	
	Window	:
	{
		open	:	function(options)
		{
			var url = options.url;
			var width = options.width ? options.width : 660;
			var height = options.height ? options.height : 540;
			var name = options.name ? options.name : JUNO_API.config.new_window_name;
			
			var newwin = window.open(url, name, 'width='+width+',height='+height+',toolbar=1,scrollbars=1,resizable=1,location=1');
			if(!newwin)
			{
				var str_prepend = ((url.match(/http(s)?:\//) == null) ? 'http://' + location.hostname + '/' : '');
				var player = getSWF(player_id);
				if(player)
				{
					player.openWindowSWF(str_prepend + url);
				}
			}
			return false;
		},
		
		open_mini:	function(options)
		{
			options.width = 250;
			options.height = 130;
			options.name = JUNO_API.config.new_mini_window_name;
			JUNO_API.Window.open(options);
		}
	},
	
	Wishlist:
	{
		addProduct : function(title_id, product_id, from)
		{
			if(arguments.length == 2)
			{
				from = '';
			}
			JUNO_API.User.doIfLogged(
				'JUNO_API.Wishlist.addProductCallback('+title_id+','+product_id+')',
				"JUNO_API.User.doLoginAndRedir('" + JUNO_API.config.url_base + '/wishlist/add/?popup=yes&from='+from+'&titleid=' + title_id + '&productid=' + product_id + "')"
			);
		},
		
		addProductCallback	: function(title_id, product_id)
		{
			$.get(
				JUNO_API.config.url_base_api + 'method=wishlist.addProduct&titleid='+title_id+'&productid='+product_id,
				function(result)
				{
					JUNO_API.Player.getSWF().showMessage(result);
				}
			);
		}
	}
}
