/**
 * @author sascha
 */
var tweetMsClass = Class.create({
	inputField:null,
	outputField:null,
	chartsInitialized:false,
	currentUrlId:null,
	twitterUser:null,
	zeroClipboard:null,
	listIsOpen:false,
	
	initialize:function()
	{
		// Homepage?
		if ($('pageHome') != null) {
			this.inputField  = $('urlform').down('input[name=url_source]');
			this.outputField = $('outform').down('input[name=outurl]');
			
			$('outform').observe('submit', function(e) { Event.stop(e); });
			
			this.inputField.observe('focus', this.handleFocus.bindAsEventListener(this));
			this.outputField.observe('focus', this.handleFocus.bindAsEventListener(this));
			this.inputField.observe('blur', this.handleFocus.bindAsEventListener(this));
			this.outputField.observe('blur', this.handleFocus.bindAsEventListener(this));
			this.outputField.observe('click', this.selectOutput.bindAsEventListener(this));
			this.inputField.observe('keyup', this.handleKeyup.bindAsEventListener(this));
			
			this.inputField.focus();
			
			$('urlform').observe('submit', this.handleSubmit.bindAsEventListener(this));
			
			if (this.inputField.hasClassName('autocreate')) {
				this.handleSubmit();
			} else if (this.inputField.hasClassName('autoedit')) {
				this.handleSubmit();
			}
		}
		
		if ($('pageStats') != null) {
			this.initCharts();
		}
		
		if ($('cbRedir') != null) {
			$('cbRedir').observe('click', this.handleAppearanceClick.bindAsEventListener(this));
		}
		
		if ($('cbBar') != null) {
			$('cbBar').observe('click', this.handleAppearanceClick.bindAsEventListener(this));
		}

		if ($('twitterUser') != null) {
			this.twitterUser = $('twitterUser').innerHTML;
		}
		
		if($('twtLogin') != null) {
			$('twtLogin').observe('click', this.handleTwitterLogin.bindAsEventListener(this));
		}
		
		if($('twtCancel') != null) {
			$('twtCancel').observe('click', this.closeTwitterLogin.bindAsEventListener(this));
		}
		
		if($('clearCookie') != null) {
	 		$('clearCookie').observe('click', function(e) {
	 			Event.stop(e);
	 			new Ajax.Request("/ajaxTwitterAction.php", {
	 				parameters:
	 				{
	 					action:'clearcookie'
	 				},
	 				
	 				onComplete:function()
	 				{
	 					location.reload();
	 				}
	 			});
	 		});
	 	}
		
		if ($('showMyUrls') != null) {
			$('showMyUrls').observe('click', this.showUrlList.bindAsEventListener(this));
		}
		
		if ($('hideMyUrls') != null) {
			$('hideMyUrls').observe('click', this.hideUrlList.bindAsEventListener(this));
		}
		
		if($('clipboardCopy') != null) {
			/*
			this.zeroClipboard = new ZeroClipboard.Client();
			this.zeroClipboard.setHandCursor(true);
			this.zeroClipboard.glue('clipboardCopy');
			
			Event.observe(window, 'resize', function() { this.zeroClipboard.reposition();}.bindAsEventListener(this));
			console.log(1);
			console.log(this.zeroClipboard);
			this.zeroClipboard.addEventListener( 'load', function(client) {
                               console.log( "movie is loaded" );
                        } );
                        
                        this.zeroClipboard.addEventListener( 'complete', function(client, text) {
                                console.log("Copied text to clipboard: " + text );
                        } );
                        
                        this.zeroClipboard.addEventListener( 'mouseOver', function(client) {
                                console.log("mouse over"); 
                        } );
                        
                        this.zeroClipboard.addEventListener( 'mouseOut', function(client) { 
                               console.log("mouse out"); 
                        } );
                        
                        this.zeroClipboard.addEventListener( 'mouseDown', function(client) { 
                                // set text to copy here
                              //  clip.setText( document.getElementById('clip_text').value );
                                
                                console.log("mouse down"); 
                        } );
                        
                        this.zeroClipboard.addEventListener( 'mouseUp', function(client) { 
                                console.log("mouse up"); 
                        } );
			
			*/
			
			
			
			$('clipboardCopy').observe('click', function (e) {
				Event.stop(e);
				this.copyToClipboard($('outform').down('input[name=outurl]').getValue());
			}.bindAsEventListener(this));
		}
	},
	
	hideUrlList:function(e)
	{
		if (e != null) Event.stop(e);
		$('showMyUrls').show();
		$('urllist').hide();
		this.listIsOpen = false;
		$('hideMyUrls').hide();
	},
	
	showUrlList:function(e)
	{
		if (e != null) Event.stop(e);
		$('showMyUrls').hide();
		$('ajaxGreen').show();
		$('showMyUrlsError').hide();
		this.listIsOpen = true;
		new Ajax.Request('/ajaxGetLinks.php', {
			onComplete:function(req)
			{
				if (req.responseJSON == null) {
					$('ajaxGreen').hide();
					$('showMyUrls').show();
					$('showMyUrlsError').update('An internal error occured, please try again later');
					$('showMyUrlsError').show();
				} else {
					var jsn = req.responseJSON;
					if (jsn.success == 1) {
						
						var tbl = $('urllist').down('table');
						var bdy = tbl.down('tbody');
						
						var trs = bdy.select('tr');
						if (trs.length > 0) {
							trs.each(function(tr1) {
								tr1.remove();
							});
						}
						
						var i = 0;
						var cls = null;
						jsn.data.each(function(dat) {
							if (i == 0) {
								cls = null;
								i = 1;
							} else {
								cls = 'alt';
								i = 0;
							}
							var row = new Element('tr', { id:'line_'+dat.id});
							
							var newTd = new Element('td');
							row.appendChild(newTd);
							newTd.addClassName(cls);
							newTd.update('<a style="color:black" href="http://'+location.hostname+'/'+dat.id+'" target="_blank">'+dat.id+'</a>');
							
//							this.addTdToTable(row, dat.id, cls);
							this.addTdToTable(row, dat.dt, cls);
							
							// Redirection type
							var newTd = new Element('td');
							row.appendChild(newTd);
							newTd.addClassName(cls);
							if (dat.rd == 'r') {
								// redirect
								newTd.update('<img class="rdimg" src="/img/arrow_redo.png" title="Redirect" alt="Redirect" />');
							} else {
								// bar
								newTd.update('<img class="rdimg" src="/img/application.png" title="Bar" alt="Bar" />');
							}
							
							var newTd = new Element('td');
							row.appendChild(newTd);
							newTd.addClassName(cls);
							newTd.update('<a style="color:black" href="'+dat.url+'" title="'+dat.url+'" target="_blank">'+dat.dom+'</a>');
							
							//this.addTdToTable(row, dat.dom, cls);
							
							var newTd = new Element('td');
							row.appendChild(newTd);
							newTd.addClassName(cls);
							newTd.addClassName('inplp');
							newTd.update('<p id="ied_'+dat.id+'">'+dat.ttl+'</p>');
							
							
							new Ajax.InPlaceEditor(newTd.down('p'), '/ajaxUpdateTitle.php', {
								formId:'inFormId_'+dat.id,
								rows:3,
								callback:function(frm, fldValue) {
									return {
										txt:fldValue,
										id:dat.id
									}
								},
								onComplete:function(req) {
									//alert('OK');
								},
								onFailure:function() {
									//alert('ERR');
								}
							});
							
							
							
							//this.addTdToTable(row, dat.rd, cls);
							
							// Actions
							var newTd = new Element('td');
							row.appendChild(newTd);
							newTd.addClassName(cls);
							newTd.update('<a href="http://stats.'+location.hostname+'/'+dat.id+'" target="_blank" class="stats" id="stats_'+dat.id+'"><img src="/img/chart_bar.png" alt="Stats" title="stats" /></a> <a href="http://'+location.hostname+'/edit.php?id='+dat.id+'#cfg" target="_self" class="edit" id="edit_'+dat.id+'"><img src="/img/cog.png" alt="Stats" title="stats" /></a> <a href="#" class="del" id="del_'+dat.id+'" title="Delete"><img src="/img/delete.png" alt="Delete" /></a>');
							var delLnk = newTd.down('a.del');
							if (delLnk != null) {
								delLnk.observe('click', function(e){
									var el = Event.element(e);
									if (el.tagName.toLowerCase() == 'img') {
										el = el.up('a');
									}
									Event.stop(e);
									if (window.confirm('Do you really want to delete this link?\nThe deletion cannot be undone!')) {
										var lnkId = el.id.replace(/del_/, "");
										new Ajax.Request('/ajaxLinkOptions.php', {
											parameters:
											{
												id:lnkId,
												action:'delete'
											},
											
											onComplete:function(req) {
												var mt = req.responseText.match(/^OK-(.*)/);
												if (mt) {
													var el1 = $('line_'+mt[1]);
													if (el1 != null) {
														el1.remove();
													}
												} else {
													alert('An internal error occured - please try again later.');
												}
											}
										});
											
										
									}
								});
							}
							
							bdy.appendChild(row);
						}.bind(this));
						
						$('ajaxGreen').hide();
						$('urllist').show();
						$('hideMyUrls').show();
					} else {
						$('ajaxGreen').hide();
						$('showMyUrlsError').update(jsn.message);
						$('showMyUrlsError').show();
					}
				}
				
			}.bind(this)
		});

	},
	
	addTdToTable:function(el, value, cls)
	{
		var newTd = new Element('td');
		el.appendChild(newTd);
		if (cls != null) {
			newTd.addClassName(cls);
		}
		newTd.update(value);
		return newTd;
	},
	
	handleAppearanceClick:function(e)
	{
		var action = '';
		var el = Event.element(e);
		if (typeof el.id != 'undefined') {
			if (el.id == 'cbRedir') {
				action='redir';
				$('cbRedir').hide();
				$('cbRedirAJAX').show();
				$('twitterlogin').hide();
				$('cbBar').disabled = true;
				this.sendAppearanceRequest(action);
			} else if (el.id == 'cbBar') {
				action='bar';
				// Loggedin?
				if (this.twitterUser == null) {
					this.showLoginBar();
				} else {
					$('cbBar').hide();
					$('cbBar').disabled = true;
					$('twitterlogin').hide();
					$('cbBarAJAX').show();
					this.sendAppearanceRequest(action);
				}
			}
		}
	},
	
	handleTwitterLogin:function(e)
	{
		$('cbBar').hide();
		$('cbBar').disabled = true;
		$('cbBarAJAX').show();
		$('twitterlogin').hide();
		$('twitterlogin_ajax').show();
		this.sendAppearanceRequest('bar');
	},
	
	closeTwitterLogin:function(e)
	{
		$('twitterlogin').hide();
		$('cbRedir').checked = 'checked';
	},
	
	showLoginBar:function()
	{
		$('twitterlogin').show();
		$('twtu').focus();
	},
	
	sendAppearanceRequest:function(action)
	{
		new Ajax.Request('/ajaxLinkOptions.php', {
			parameters:
			{
				id:this.currentUrlId,
				action:action,
				u:$F('twtu'),
				p:$F('twtp'),
				setcookie:($('ccb').checked == true)
			},
			
			onComplete:function(req)
			{
				
				$('cbRedirAJAX').hide();
				//$('cbBar').show();
				$('cbBarAJAX').hide();
				$('cbRedir').disabled = false;
				$('cbBar').disabled = false;
				$('twitterlogin_ajax').hide();
				
				var visibleAgain = false;
				
				if (req.status == 200) {
					if (req.responseJSON != null) {
						if (req.responseJSON.success == 1) {
							var th1 = null;
							if (this.listIsOpen) {
//								console.log('line_'+this.currentUrlId);
								th1 = $('line_'+this.currentUrlId);
							} else {
								//alert('no');
							}
					//		console.log(th1);
							if (req.responseJSON.action == 'redir') {
								$('cbRedirOk').show();
								visibleAgain = true;

								if (th1 != null) {
									th1.down('img.rdimg').src = '/img/arrow_redo.png';
								}
								
								window.setTimeout(function() { $('cbRedirOk').hide(); $('cbRedir').show(); }, 3000);
							} else if (req.responseJSON.action == 'bar') {
								$('cbBarOk').show();
								visibleAgain = true;
								if (th1 != null) {
									th1.down('img.rdimg').src = '/img/application.png';
								}
								window.setTimeout(function() { $('cbBarOk').hide(); $('cbBar').show(); }, 3000);
							}
						} else {
							alert(req.responseJSON.message);
						}
					}
				} else {
					alert('An error occured saving the appearance settings.\nPlease try again later.')
				}
				
				if(!visibleAgain) {
					$('cbRedir').show();
					$('cbBar').show();
				}
			}.bind(this)
		});
	},
	
	handleFocus:function(e)
	{
		if (Prototype.Browser.IE) {
			return;
		}
		var el = Event.element(e);
		var eType = e.type;
		el.select();
		if (eType == 'focus') {
			el.addClassName('focused');
		} else {
			el.removeClassName('focused');
		}
	},
	
	handleSubmit:function(e)
	{
		if (e != null) {
			Event.stop(e);
		}
		var inputUrl = this.inputField.getValue();
		if (inputUrl == '' || inputUrl.match(/^\s+$/) || inputUrl == 'http://') {
			return;
		}
		if (!inputUrl.match(/^https?\:\/\//i)) {
			this.showMessage('Invalid URL!');
			return;
		}
		
		this.hideMessage();
		
		// AJAX loader
		$('urlform').down('button').hide();
		$('ajaxloader').show();
		this.inputField.disabled = true;
		
//			<form id="urlform" method="post" action="/create.php" class="autoedit ae_{autoedit_id}">
		
		var aeditId = '';
		var editVal = this.inputField.hasClassName('autoedit');
		if (editVal) {
			// Get edit id
			if ($('urlform').hasClassName('autoedit')) {
				var cls = $('urlform').classNames();
				cls.each(function(cl) {
					var mtc = cl.match(/^ae_(.*)/);
					if (mtc) {
						aeditId = mtc[1];
					}
				})
			}
		}
		
		// Handle URL
		new Ajax.Request('/e.php', {
			parameters:
			{
				url:this.inputField.getValue(),
				edit:editVal,
				id:aeditId
			},
			onComplete:function(req)
			{
				if (this.listIsOpen) {
					this.showUrlList();
				}
				$('urlform').down('button').show();
				$('ajaxloader').hide();
				this.inputField.disabled = false;
				if (req.status != 200 || req.responseJSON == null) {
					this.showMessage('Sorry, an internal error occured. Please try again later.');
					return;
				}
				
				var newUrl = req.responseJSON.url;
				if (!newUrl) {
					if (req.responseJSON.message != '' && req.responseJSON.message != null) {
						this.showMessage(req.responseJSON.message);
					}
					else {
						this.showMessage('Sorry, an internal error occured. Please try again later.');
					}
					return;
				}
				
				if (req.responseJSON.tUser != null && req.responseJSON.loggedin == 0) {
					$('twtu').setValue(req.responseJSON.tUser);
				}
				
				
				
				var redirType = req.responseJSON.redir;
				if (redirType == 'REDIR') {
					$('cbRedir').checked = true;
					$('cbBar').checked   = false;
				} else if (redirType == 'TWEETBAR') {
					$('cbRedir').checked = false;
					$('cbBar').checked   = true;
					
					
					if (req.responseJSON.loggedin == 0) {
						$('twitterlogin').show();
					}
					
//					$obj->tUser = $twitterUserInfo['login'];
//					$obj->tImage =
				}
				
				this.outputField.setValue(newUrl);
				$('urlCopy').setAttribute('href', newUrl);
				$('statsLink1').update(req.responseJSON.statsurl);
				this.currentUrlId = req.responseJSON.urlId;
				$('statsLink1').href=req.responseJSON.statsurl;
				//this.outputField.select();
				$('output_default').hide();
				$('output').show();
				this.outputField.focus();
				this.outputField.select();
//				this.zeroClipboard.reposition();
			}.bind(this)
		});
	},
	
	selectOutput:function(e)
	{
		this.outputField.select();
	},
	
	handleKeyup:function(e)
	{
		if ($('message').getStyle('display') != 'none') {
			if (this.inputField.getValue() == '') {
				this.hideMessage();
			}
		}
	},
	
	showMessage:function(msg)
	{
		$('message').update(msg);
		new Effect.Appear($('message'));
	},
	
	hideMessage:function()
	{
		$('message').hide();
	},
	
	
	showCharts:function(jsonData)
	{
		//console.log(jsonData);
		// BASIC DATA
		var dv = $('dynamic');
		dv.down('span.targetUrl').update(jsonData.url);
		dv.down('span.urlCreated').update(jsonData.url_created);
		//dv.down('span.firstAccess').update(jsonData.first_access);
		//dv.down('span.lastAccess').update(jsonData.last_access);
		dv.down('span.visitorCount').update(parseInt(jsonData.number_bots) + parseInt(jsonData.number_users));
		dv.down('span.botCount').update(jsonData.number_bots);
		dv.down('span.humanCount').update(jsonData.number_users);
		
		// VIEWS
		var viewsData = jsonData.views;
		var views = new google.visualization.DataTable();
		views.addColumn('string', 'Date');
		views.addColumn('number', 'Visitors');
		views.addRows(viewsData.length);
		
		var i = 0;
		viewsData.each(function(row) {
			views.setValue(i, 0, row.date);
			views.setValue(i, 1, parseInt(row.c));
			i = i +1;
		});
		var viewsChart = new google.visualization.AreaChart($('chart_views'));
        viewsChart.draw(views, {width: 700, height: 240, legend: 'bottom', title: 'Visits'});


		// Browser Names
		var browserNamesData = jsonData.browserNames;
		var browserNames = new google.visualization.DataTable();
		browserNames.addColumn('string', 'Browser');
		browserNames.addColumn('number', 'Count');
		browserNames.addRows(browserNamesData.length);
		
		var i = 0;
		browserNamesData.each(function(row) {
			if (row.name == 'unknown') row.name = '(unknown)';
			browserNames.setValue(i, 0, row.name);
			browserNames.setValue(i, 1, parseInt(row.c));
			i = i +1;
		});
				
		var browserNamesChart = new google.visualization.PieChart($('chart_browsernames'));
		browserNamesChart.draw(browserNames, {width: 700, height: 240, is3D: true, title: ''});
		
		// BrowserOs
		var browserOsData = jsonData.browserOs;
		var browserOs = new google.visualization.DataTable();
		browserOs.addColumn('string', 'Operating System');
		browserOs.addColumn('number', 'Count');
		browserOs.addRows(browserOsData.length);
		
		var i = 0;
		browserOsData.each(function(row) {
			if (row.os == 'unknown') row.os = '(unknown)';
			browserOs.setValue(i, 0, row.os);
			browserOs.setValue(i, 1, parseInt(row.c));
			i = i +1;
		});
				
		var browserOsChart = new google.visualization.PieChart($('chart_browseros'));
		browserOsChart.draw(browserOs, {width: 700, height: 240, is3D: true, title: ''});
		
		
		// Countries
		var countryData = jsonData.countries;
		var country = new google.visualization.DataTable();
		country.addColumn('string', 'Countries');
		country.addColumn('number', 'Count');
		country.addRows(countryData.length);
		
		var i = 0;
		countryData.each(function(row) {
			country.setValue(i, 0, row.name);
			country.setValue(i, 1, parseInt(row.c));
			i = i +1;
		});
		
   	    var options = {};
	    options['dataMode'] = 'regions';

      var container = $('chart_country');
      var geomap = new google.visualization.GeoMap(container);
      geomap.draw(country, { dataMode:'regions', width: 718, height: 500});

		// Referrers
		var refTbl = $('referrers');
		var tBd    = refTbl.down('tbody');
		if (jsonData.referrers.length > 0) {
			var i = 1;
			jsonData.referrers.each(function (ref) {
				var newTr = new Element('tr');
				tBd.appendChild(newTr);
				newTr.addClassName('t'+i);
				
				var td1 = new Element('td');
				newTr.appendChild(td1);
				td1.update(ref.u);
				
				var td2 = new Element('td');
				newTr.appendChild(td2);
				td2.update(ref.c);
				
				if (i == 2) i = 1; else i = 2;
			});
		}
	
		//var countryChart = new google.visualization.PieChart($('chart_country'));
	//	countryChart.draw(country, {width: 700, height: 240, is3D: true, title: 'Countries'});
	},
	
	updateCharts:function()
	{
		var clsNm = $('pageStats').className;
		var cryptLink = clsNm.replace(/^link_/, "");
		
		new Ajax.Request('/ajaxStats.php', {
			
			parameters:
			{
				id:cryptLink
			},
			
			onComplete:function(req)
			{
				if (req.responseJSON) {
					var jsonObj = req.responseJSON;
					this.showCharts(jsonObj);
					return;
				} else {
					alert('An error occured fetching the statistics data.\nPlease try again at a later time.');
				}
			}.bind(this)
		});
		
	},
	
	initCharts:function()
	{
		if (this.chartsInitialized == false) {
			this.chartsInitialized = true;
			this.updateCharts();
		}
	},
	
	copyToClipboard:function(s)
	{
		//this.zeroClipboard.setText(s);
		
		if( window.clipboardData && clipboardData.setData )
		{
			clipboardData.setData("Text", s);
		}
		else
		{
			alert("Please press Ctrl+C to copy to your clipboard");
			/*
			// You have to sign the code to enable this or allow the action in about:config by changing
			//user_pref("signed.applets.codebase_principal_support", true);
			netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
	
			var clip = Components.classes['@mozilla.org/widget/clipboard;[[[[1]]]]'].createInstance(Components.interfaces.nsIClipboard);
			if (!clip) return;
	
			// create a transferable
			var trans = Components.classes['@mozilla.org/widget/transferable;[[[[1]]]]'].createInstance(Components.interfaces.nsITransferable);
			if (!trans) return;
	
			// specify the data we wish to handle. Plaintext in this case.
			trans.addDataFlavor('text/unicode');
	
			// To get the data from the transferable we need two new objects
			var str = new Object();
			var len = new Object();
	
			var str = Components.classes["@mozilla.org/supports-string;[[[[1]]]]"].createInstance(Components.interfaces.nsISupportsString);
	
			var copytext=s;
	
			str.data=copytext;
	
			trans.setTransferData("text/unicode",str,copytext.length*[[[[2]]]]);
	
			var clipid=Components.interfaces.nsIClipboard;
	
			if (!clip) return false;
	
			clip.setData(trans,null,clipid.kGlobalClipboard);
			*/
		}
		
	}
	
});

var tweetMs;

Event.observe(window, 'load', function() {
	tweetMs = new tweetMsClass();
});
