// JavaScript Document
function addUrlForm(f) {
	urlr = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
	if(f !== null) {
		if(document.getElementById(f)) {
			i = document.getElementById(f);
			if(f == 'url') {
				e = document.getElementById('url-error');
				if(urlr.test(i.value) === false) {
					e.innerHTML = '<img src="/images/icons/invalid.png" /> Invalid URL';
					e.style.display == 'inline-block';
					document.getElementById('custom').disabled = true;
					document.getElementById('title').disabled = true;
					document.getElementById('quick').disabled = true;
					document.getElementById('advan').disabled = true;
				} else {
					e.innerHTML = '<img src="/images/icons/valid.png" />';
					e.style.display == 'inline-block';
					document.getElementById('custom').disabled = false;
					document.getElementById('title').disabled = false;
					document.getElementById('quick').disabled = false;
					document.getElementById('advan').disabled = false;
				}
			} else if(f == 'generatecode') {
				if(document.getElementById('url').value != '' && urlr.test(document.getElementById('url').value) !== false) {
					document.getElementById('custom').disabled = true;
					p = 'url='+escape(document.getElementById('url').value);
					if(window.XMLHttpRequest) {
						xhttp = new XMLHttpRequest();
					} else if(window.ActiveXObject) {
						xhttp = new ActiveXObject("Microsoft.XMLHTTP");
					}
					if(xhttp != null) {
						xhttp.onreadystatechange = function() {
							if(xhttp.readyState == 4) {
								if(xhttp.status == 200) {
									if(xhttp.responseText != '') {
										document.getElementById('custom').value = xhttp.responseText;
									}
								}
							}
						};
						xhttp.open('POST', '/ajax/generatecode', true);
						xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
						xhttp.setRequestHeader('Content-length', p.length);
						xhttp.setRequestHeader('Connection', 'close');
						xhttp.send(p);
					}
				}
			} else if(f == 'grabtitle') {
				if(document.getElementById('url').value != '' && urlr.test(document.getElementById('url').value) !== false) {
					document.getElementById('title').disabled = true;
					p = 'url='+escape(document.getElementById('url').value);
					if(window.XMLHttpRequest) {
						xhttp = new XMLHttpRequest();
					} else if(window.ActiveXObject) {
						xhttp = new ActiveXObject("Microsoft.XMLHTTP");
					}
					if(xhttp != null) {
						xhttp.onreadystatechange = function() {
							if(xhttp.readyState == 4) {
								if(xhttp.status == 200) {
									if(xhttp.responseText != '') {
										document.getElementById('title').value = xhttp.responseText;
									}
								}
							}
						};
						xhttp.open('POST', '/ajax/grabtitle', true);
						xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
						xhttp.setRequestHeader('Content-length', p.length);
						xhttp.setRequestHeader('Connection', 'close');
						xhttp.send(p);
					}
				}
			} else if(f == 'quick') {
				document.getElementById('addButton').click();
			} else if(f == 'advan') {
				document.getElementById('addurlhidden').style.display = 'block';
				document.getElementById('addButton').style.display = 'block';
				document.getElementById('quick').style.display = 'none';
				i.style.display = 'none';
				addUrlForm('generatecode');
				addUrlForm('grabtitle');
			}
		}
	}
}
function share(type, data) {
	if(type != '' && data != '') {
		if(type === 'facebook') {
			FB.Connect.requireSession(function() {
				FB.Connect.streamPublish('', {
					'name':data.title+' - via Shrink My URL',
					'href':data.url
				});
			});
		} else if(type === 'twitter') {
			if(window.XMLHttpRequest) {
				xhttp = new XMLHttpRequest();
			} else if(window.ActiveXObject) {
				xhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			if(xhttp != null) {
				xhttp.onreadystatechange = function() {
					if(xhttp.readyState == 4) {
						if(xhttp.status == 200) {
							if(xhttp.responseText == 'false') {
								l = (screen.width-800)/2;
								t = (screen.height-400)/2;
								window.open('/twitter/auth', 'Twitter-Auth', 'width=800,height=400,resizable=no,toolbar=no,menubar=no,top='+t+',left='+l+',screenY='+t+',screenX='+l);
							} else {
								j = json_parse(xhttp.responseText);
								if(j.auth != 1) {
									l = (screen.width-800)/2;
									t = (screen.height-400)/2;
									window.open('/twitter/auth/'+j.token, 'Twitter-Auth', 'width=800,height=400,resizable=no,toolbar=no,menubar=no,top='+t+',left='+l+',screenY='+t+',screenX='+l);
								} else {
									if(window.XMLHttpRequest) {
										xhttp = new XMLHttpRequest();
									} else if(window.ActiveXObject) {
										xhttp = new ActiveXObject("Microsoft.XMLHTTP");
									}
									if(xhttp != null) {
										xhttp.onreadystatechange = function() {
											if(xhttp.readyState == 4) {
												if(xhttp.status == 200) {
													if(xhttp.responseText == 'true') {
														alert('Tweet Sent');
													} else {
														alert('Error Posting to Twitter');
													}
												}
											}
										};
									}
									p = 'title='+escape(data.title)+'&url='+data.url;
									xhttp.open('POST', '/twitter/share', true);
									xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
									xhttp.setRequestHeader('Content-length', p.length);
									xhttp.setRequestHeader('Connection', 'close');
									xhttp.send(p);
								}
							}
						}
					}
				};
				xhttp.open('GET', '/ajax/twitter', true);
				xhttp.send();
			}
		} else if(type === 'plain') {
			document.body.scrollTop;
			if(!document.getElementById('map-container')) {
				document.body.innerHTML += '<div id="map-container" style="opacity:0;filter:alpha(opacity = 0);"><div style="float:right;margin:10px;cursor:pointer;"><img src="/images/icons/close.png" onclick="hideMap();" /></div><div id="map"></div></div>';
			}
			document.getElementById('map-container').style.width = '400px';
			document.getElementById('map-container').style.height = '400px';
			document.getElementById('map-container').style.left = '30%';
			document.getElementById('map-container').style.top = '20%';
			document.getElementById('map').style.display = 'block';
			document.getElementById('map').style.width = '92%';
			document.getElementById('map').style.height = '80%';
			document.getElementById('map').style.padding = '5px';
			document.getElementById('map').style.overflow = 'auto';
			document.getElementById('map').style.backgroundImage = 'none';
			new Ajax.Updater('map', '/ajax/plain', {
				parameters: data
			});			
			fade('map-container');
		}
	}
}
var TimeToFade = 1000.0;
function fade(eid) {
	var element = document.getElementById(eid);
	if(element == null)
	  return;
	 
	if(element.FadeState == null) {
	  if(element.style.opacity == null || element.style.opacity == '' || element.style.opacity == '1') {
		element.FadeState = 2;
	  } else {
		element.FadeState = -2;
	  }
	}
	if(element.FadeState == 1 || element.FadeState == -1)   {
	  element.FadeState = element.FadeState == 1 ? -1 : 1;
	  element.FadeTimeLeft = TimeToFade - element.FadeTimeLeft;
	} else {
	  element.FadeState = element.FadeState == 2 ? -1 : 1;
	  element.FadeTimeLeft = TimeToFade;
	  setTimeout("animateFade(" + new Date().getTime() + ",'" + eid + "')", 33);
	}  
}
function animateFade(lastTick, eid) {  
	var curTick = new Date().getTime();
	var elapsedTicks = curTick - lastTick;
   
	var element = document.getElementById(eid);
   
	if(element.FadeTimeLeft <= elapsedTicks) {
	  element.style.opacity = element.FadeState == 1 ? '1' : '0';
	  element.style.filter = 'alpha(opacity = ' + (element.FadeState == 1 ? '100' : '0') + ')';
	  element.FadeState = element.FadeState == 1 ? 2 : -2;
	  return;
	}
	element.FadeTimeLeft -= elapsedTicks;
	var newOpVal = element.FadeTimeLeft/TimeToFade;
	if(element.FadeState == 1) {
	  newOpVal = 1 - newOpVal;
	}
	element.style.opacity = newOpVal;
	element.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')'; 
	setTimeout("animateFade(" + curTick + ",'" + eid + "')", 33);
}
function showMap(lon, lat, c) {
	if(lon !== '' && lat !== '' && c !== '') {
		document.body.scrollTop;
		if(!document.getElementById('map-container')) {
			document.body.innerHTML += '<div id="map-container" style="opacity:0;filter:alpha(opacity = 0);"><div style="float:right;margin:10px;cursor:pointer;"><img src="/images/icons/close.png" onclick="hideMap();" /></div><div id="map"></div></div>';
		}
		fade('map-container');
		setTimeout(function() {
			var map;
			var geocoder = new google.maps.Geocoder();
			var latlng = new google.maps.LatLng(lat, lon);
			if (geocoder) {
				geocoder.geocode( {'address': c}, function(results, status) {
					if (status == google.maps.GeocoderStatus.OK) {
						var myOptions = {
						  zoom: 5,
						  center: results[0].geometry.location,
						  mapTypeId: google.maps.MapTypeId.HYBRID
						}
						map = new google.maps.Map(document.getElementById('map'), myOptions);
						//map.setCenter(latlng, 13);
						var image = '/images/icons/pin_big.png';
						var beachMarker = new google.maps.Marker({
							position: latlng,
							map: map,
							icon: image
						});
					} else {
						alert("Geocode was not successful for the following reason: " + status);
					}
				});
			}
			if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
				document.body.scrollTop;
			} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
				document.documentElement.scrollTop;
			}
			document.getElementById('map').style.display = 'block';
		}, 2500);
	}
}
function showMapAll(code) {
	document.body.scrollTop;
	if(!document.getElementById('map-container')) {
		document.body.innerHTML += '<div id="map-container" style="opacity:0;filter:alpha(opacity = 0);"><div style="float:right;margin:10px;cursor:pointer;"><img src="/images/icons/close.png" onclick="hideMap();" /></div><div id="map"></div></div>';
	}
	fade('map-container');
	setTimeout(function() {
		var map;
		var geocoder = new google.maps.Geocoder();
		if (geocoder) {
			geocoder.geocode( {'address': 'United Kingdom'}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					var myOptions = {
					  zoom: 3,
					  center: results[0].geometry.location,
					  mapTypeId: google.maps.MapTypeId.TERRAIN
					}
					//map.setCenter(latlng, 13);
					if(window.XMLHttpRequest) {
						xhttp = new XMLHttpRequest();
					} else if(window.ActiveXObject) {
						xhttp = new ActiveXObject("Microsoft.XMLHTTP");
					}
					var p = 'url='+code;
					if(xhttp != null) {
						xhttp.onreadystatechange = function() {
							if(xhttp.readyState == 4) {
								if(xhttp.status == 200) {
									if(xhttp.responseText != '') {
										map = new google.maps.Map(document.getElementById('map'), myOptions);
										var latlon = xhttp.responseText.split(',');
										for(var i = 0; i < latlon.length; i++) {
											latlon[i] = latlon[i].split('|');
											latlng = new google.maps.LatLng(latlon[i][0], latlon[i][1]);
											var image = '/images/icons/marker.png';
											var beachMarker = new google.maps.Marker({
												position: latlng,
												map: map,
												icon: image
											});
										}
									}
								}
							}
						};
						xhttp.open('POST', '/ajax/latlon', true);
						xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
						xhttp.setRequestHeader('Content-length', p.length);
						xhttp.setRequestHeader('Connection', 'close');
						xhttp.send(p);
					}
				} else {
					alert("Geocode was not successful for the following reason: " + status);
				}
			});
		}
		if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
			document.body.scrollTop;
		} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
			document.documentElement.scrollTop;
		}
		document.getElementById('map').style.display = 'block';
	}, 2500);
}
function hideMap() {
	fade('map-container');
	setTimeout(function() { window.location.href = window.location.href; }, 1200);
}
function randompassword() {
	a = arguments;
	if(a.length > 0) {
		if((e = document.getElementById('randompassword')) !== false) {
			c = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXZ0123456789'.toArray();
			p = '';
			for(var i = 0; i < 7; i++) {
				r = Math.ceil(Math.random()*c.length);
				p += c[r];
			}
			if(p.length == 7) {
				for(var x = 0; x < a.length; x++) {
					document.getElementById(a[x]).value = p;
				}
				e.innerHTML = '<strong>Password</strong> '+p;
				alert('Please make note of the new password!');
			}
		}
	}
}
function insertAfter(parent, node, referenceNode) {
  parent.insertBefore(node, referenceNode.nextSibling);
}
function addRule(t) {
	if(t.empty() === false) {
		if(Object.isElement($(t))) {
			tr = Builder.node('tr');
			td1 = Builder.node('td', {'class':'first'});
			td2 = Builder.node('td');
			td3 = Builder.node('td');
			sel = Builder.node('select', {name:'perm[]'});
			td1.appendChild(Builder.node('input', {name:'type[]',type:'hidden',value:t}));
			td1.appendChild(Builder.node('input', {name:'rule[]',type:'text',value:'',onkeyup:"ruleOptions(this, '"+t+"');",onblur:"$('optHelp').remove();"}));
			sel.appendChild(Builder.node('option', {value:'deny'}, 'Deny'));
			sel.appendChild(Builder.node('option', {value:'allow'}, 'Allow'));
			td2.appendChild(sel);
			td3.appendChild(Builder.node('img', {src:'/images/icons/cancel.png',onclick:'deleteRule(this);',style:'cursor:pointer'}));
			tr.appendChild(td1);
			tr.appendChild(td2);
			tr.appendChild(td3);
			$(t).appendChild(tr);
		}
	}
}
function deleteRule(td) { td.up(1).remove(); }
function ruleOptions(e, t) {
	if(t.empty() === false) {
		if(Object.isElement(e)) {
			p = e.up(3).getOffsetParent().viewportOffset();
			o = e.viewportOffset();
			w = e.getWidth()-2;
			h = e.getHeight();
			t = o[1]-p[1] + h;
			l = o[0]-p[0];
			if($('optHelp') === null) {
				opt = Builder.node('div', {id:'optHelp'}).setStyle({'position':'absolute','top':t+'px', 'left':l+'px','width':w+'px'}).update('<span>Hello</span>');
				e.up(1).appendChild(opt);
			}
			
		}
	}
}


