/*
Function: $get
	This function provides access to the "get" variable scope + the element anchor
	
Version: 1.2
 
Arguments:
	key - string; optional; the parameter key to search for in the url's query string (can also be "#" for the element anchor)
	url - url; optional; the url to check for "key" in, location.href is default
 
Example:
	>$get("foo","http://example.com/?foo=bar"); //returns "bar"
	>$get("foo"); //returns the value of the "foo" variable if it's present in the current url(location.href)
	>$get("#","http://example.com/#moo"); //returns "moo"
	>$get("#"); //returns the element anchor if any, but from the current url (location.href)
	>$get(,"http://example.com/?foo=bar&bar=foo"); //returns {foo:'bar',bar:'foo'}
	>$get(,"http://example.com/?foo=bar&bar=foo#moo"); //returns {foo:'bar',bar:'foo',hash:'moo'}
	>$get(); //returns same as above, but from the current url (location.href)
	>$get("?"); //returns the query string (without ? and element anchor) from the current url (location.href)
 
Returns:
	Returns the value of the variable form the provided key, or an object with the current GET variables plus the element anchor (if any)
	Returns "" if the variable is not present in the given query string
 
Credits:
		Regex based on http://www.netlobo.com/url_query_string_javascript.html
		Function by Jens Anders Bakke, webfreak.no
*/
function $get(key,url){
	if(arguments.length < 2) url =location.href;
	if(arguments.length > 0 && key != ""){
		if(key != "#" && key != "?"){
			var regex = new RegExp("[?&]"+key+"=([^&#]*)");
			var results = regex.exec(url);
			return (results == null )? "" : results[1];
		}else if(key == "#"){
			var regex = new RegExp("[#]([^$]*)");
			var results = regex.exec(url);
			return (results == null )? "" : results[1];
		} else if(key == "?"){
			var regex = new RegExp("[?]([^#$]*)");
			var results = regex.exec(url);
			return (results == null )? "" : results[1];
		}
	} else {
		url = url.split("?");
		var results = {};
			if(url.length > 1){
				url = url[1].split("#");
				if(url.length > 1) results["hash"] = url[1];
				url[0].split("&").each(function(item,index){
					item = item.split("=");
					results[item[0]] = item[1];
				});
			}
		return results;
	}
}

/*
Function: $pngfix
	This function fixes png alphatransparency for png images used on a page (not backgrounds)
	
Version: 1
 
Arguments:
	blankPath - string; a path to a blank .gif file
	pngs - array; optional; an array of img elements, if not provided it will use an array of all img tags with a .png file as source 
 
Example:
	>$pngfix("/assets/img/blank.gif",$$('img[src$=".png"]')); //
	>$pngfix("/assets/img/blank.gif"); //returns the value of the "foo" variable if it's present in the current url(location.href)
 
Returns:
	Returns the value of the variable form the provided key, or an object with the current GET variables plus the element anchor (if any)
	Returns "" if the variable is not present in the given query string
 
Credits:
		Regex based on http://www.netlobo.com/url_query_string_javascript.html
		Function by Jens Anders Bakke, webfreak.no
*/
function $pngfix(blankPath,pngs){
	if (!arguments.length) var blankPath = "blank.gif";
	if (arguments.length < 2) var pngs = $$('img[src$=".png"]');
	pngs.each(function(obj){
		var _width = obj.width;
		var _height = obj.height;
		obj.setStyles({
			"filter": "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/" + obj.getProperty('src') + "',sizingMethod='scale')",
			"width": _width + 'px',
			"height": _height + 'px'
		});
		obj.setProperty("src", blankPath);
	});
}
/**
 * @author Jens Anders Bakke, eddamedia.no
 * Site functionality, loads Event and Tools functions for the various sections
 * @requires Tools and Events collections
 */
var Site = {
	/**
	 * Site.start()
	 * Detects the current site, loads the correct function (eg. Site.edit)
	 */
	start: function(options){
		this.options = options;
		
		// if minigmap
		/*if($('minigmap')){
			var el = $('minigmap');
			var pointer = Json.evaluate(el.getProperty('rel'));
			Tools.minigmap(el,pointer.Lat,pointer.Long);
		}*/
		// add a lot of events
		Site.events();
		if(window.ie6) Tools.pngfix();
	},
	/**
	 * 
	 * @param {Object} options
	 */
	events: function(options){
		this.options = options;
		// Ping to keep the php session ;)
		//Tools.ping();
		_Events.onemorefile();
		_Events.croppr();
		_Events.mapr();
		_Events.mapr2();
		_Events.maxcheck($$('.boxfieldset'), 3);
		_Events.reportthis();
		// add the advanced on/off event
		_Events.onoff();
		// add doconfirm events
		_Events.submitonclick();
	}
};

/**
 * @author Jens Anders Bakke, eddamedia.no
 * "Tools" function collection
 * Holds functions like croppr() and mapr()
 */
var Tools = {
	/**
	 * Tools.croppr(), loads a croppr of the given parameters
	 * @param {Object} img (img src, can be url or path)
	 * @param {Object} x (width of the crop area)
	 * @param {Object} y (height of the crop area)
	 */
	croppr: function(img,x,y,typeid,item){
		cool = new Croppr(img, {
			crop: [x,y], 
			url: function(v){
				new Ajax('croppr.php',{
					method: 'post', 
					postBody:'src='+img+'&typeid='+typeid+'&'+Object.toQueryString(v), 
					onComplete: function(r){
						cool.destroy();
						if($E('.profileimg')){
							(function(){
								Tools.imgreload($E('.profileimg'));
								Tools.imgreload($E('.me .userthumb'));
							}).delay(1000);
							(function(){
								Tools.imgreload($E('.profileimg'));
								Tools.imgreload($E('.me .userthumb'));
							}).delay(5000);
							(function(){
								Tools.imgreload($E('.profileimg'));
								Tools.imgreload($E('.me .userthumb'));
							}).delay(10000);
						}
					}
				}).request();
			},
			onExit: function(){
				item.checked=false;
			},
			background:'#000'});
	},
	/**
	 * fix the png! :D
	 */
	pngfix: function(){
		var blankPath = "/assets/images/blank.gif";
		var pngs = $$('img[src$=".png"]');
		pngs.each(function(obj){
			var _width = obj.width;
			var _height = obj.height;
			obj.setStyles({
				"filter": "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/" + obj.getProperty('src') + "',sizingMethod='scale')",
				"width": _width+'px',
				"height": _height+'px'
			});
			obj.setProperty("src", blankPath);
		});
	},
	loginbox: function(){
		var myControl = new Accordion('#loginbox h2', '#loginbox form ', {
				opacity: false,
				fixedHeight:200,
				onActive: function(toggler, element){
					toggler.addClass("on");
				},
			 
				onBackground: function(toggler, element){
					toggler.removeClass("on");
				}
			}, $('loginbox'));
	},
	/**
	 * 
	 */
	imgreload: function(img){
		var now = new Date();
		img.setProperty("src",img.getProperty("src")+"?"+now.getTime());
	},
	/**
	 * Tools.mapr
	 * @param {Object} options
	 */
	mapr: function(options){
		mapOptions = options;
		mapContainer = new Element('div').setStyles({
		      position: 'absolute',
		      top: '0',
		      left: '0', 
		      overflow: 'hidden', 
		      width: '100%',
		      height: window.getScrollHeight()+'px'
		    });
		//generate new url if lat or long is set
		if(mapOptions.Lat.value != "" && mapOptions.Long.value != ""){
			var paper = $get("paper",mapOptions.url);
			var newurl = mapOptions.url.split("?")[0];
			if(paper != ""){
				mapOptions.url = newurl+"?paper="+paper+"&lat="+mapOptions.Lat.value+"&long="+mapOptions.Long.value;
			}else{
				mapOptions.url = newurl+"?lat="+mapOptions.Lat.value+"&long="+mapOptions.Long.value;
			}
			
		}
		// check for which loader to load, and then load the content
			mapContent = new Element('form',{
				'id':'maprform',
				'styles': {
					'display': 'block',
					'border': '6px solid #fff',
					'background': '#fff',
					'width':'650px',
					'height':'450px',
					'margin':window.getScrollTop()+(window.getHeight()/2)-225+'px auto 0 auto'
			    }
			});
			mapFrame = new Element('iframe',{ 
				'src':mapOptions.url,
				'styles': {
					'display': 'block',
					'border': 'none',
					'background': '#fff',
					'width':'500px',
					'height':'450px',
					'float':'left'
			    }
			});
			mapForm = '<fieldset class="maplat"><label for="long">Lengdegrad:</label><input type="text" name="long" id="long" value="'+mapOptions.Long.value+'"></fieldset><fieldset class="maplong"><label for="lat">Breddegrad:</label><input type="text" name="lat" id="lat" value="'+mapOptions.Lat.value+'"></fieldset><fieldset><input type="submit" value="Velg" id="maprsubmit"> <input type="reset" value="Avbryt" id="maprcancel"></fieldset><div class="info"><p>Du kan klikke og dra i kartet for å endre utsnitt.</p><p>Med knappene oppe til venstre kan du zoome inn og ut med +/- og endre utsnitt med pilene.</p></div><input type="hidden" name="zoom" id="zoom">';
			mapContent.setHTML(mapForm);
			mapFrame.injectTop(mapContent);
			
		mapTrans = mapContainer.clone(false).setStyles({
	      visibility: 'hidden',
	      background: '#333',
	      overflow: 'visible'
	    }).setProperty('id','maprbg').injectInside(document.body);
	    new Fx.Style(mapTrans, 'opacity', {duration: 800,onComplete:function(){
				mapContainer.setProperty('id', 'mapr').injectInside(document.body);
				mapContent.injectInside($('mapr'));
				$('maprsubmit').addEvent('click',function(e){
					e = new Event(e).stop();
					mapOptions.Lat.value = $('lat').value;
					mapOptions.Long.value = $('long').value;
					mapOptions.Lat.fireEvent('change');
					mapOptions.Long.fireEvent('change');
					new Fx.Style($('maprbg'), 'opacity', {duration: 800,onStart:function(){
							$('maprform').removeEvents('submit');
							$('mapr').remove();
						},onComplete:function(){
							$('maprbg').remove();
					}}).custom(0.8, 0.0);
				});// addEvent
				$('maprcancel').addEvent('click',function(e){
					e = new Event(e).stop();
					new Fx.Style($('maprbg'), 'opacity', {duration: 800,onStart:function(){
							$('maprform').removeEvents('submit');
							$('mapr').remove();
						},onComplete:function(){
							$('maprbg').remove();
					}}).custom(0.8, 0.0);
				});//addEvent
			}}).custom(0.0, 0.8);
	},
	/**
	 * Tools.minigmap(), loads a GMap without controllers and dragging disbled, with one point!
	 * @param {Object} el
	 * @param {Object} Lat
	 * @param {Object} Long
	 */
	minigmap: function(el,Lat,Long,zoom){
		if (GBrowserIsCompatible()) {
			// make map
			var map = new GMap(el);
			// no dragging
			map.disableDragging();
			// add zoomer
			map.addControl(new GSmallMapControl());
			// center and zoom
			map.centerAndZoom(new GPoint(Long, Lat), 5);
			
			// add the amrker
			var point = new GPoint(Long, Lat);
			var marker = new GMarker(point);
			map.addOverlay(marker);
		}
		
	},
	/**
	 * 
	 * @param {Object} msg
	 */
	doconfirm: function(msg){
		if(confirm(msg)){
			return true;
		} else {
			return false;
		}
	},
	/**
	 * 
	 * @param {Object} options
	 */
	addreport: function(url,text,opener){
		if(!$('reportform')){
			report = {};
			pos = opener.getPosition();
			size = opener.getSize().size;
			report.form = new Element('form', {
			    'method': 'post',
			    'action': url,
				'events': {
					'submit': function(e){
					   report.submit.disabled = "true";
					}
				},
				'styles' : {
					'top':pos.y+size.y+'px',
					'left':pos.x+'px'
				},
				'id': 'reportform'
			});
			report.fieldset = new Element('fieldset').injectInside(report.form);
			report.legend = new Element('legend').injectInside(report.fieldset).setHTML("Begrunn din rapport");
			report.h2 = new Element('h2').injectInside(report.fieldset).setHTML(text);
			report.area = new Element('textarea', {
			    'id': 'reportarea',
			    'class': 'reportarea',
				'name': 'reason'
			}).injectInside(report.fieldset);
			report.submit = new Element('input', {
			    'type': 'submit',
			    'value': ' Rapporter '
			}).injectInside(report.fieldset);
			report.cancel = new Element('input', {
				'type': 'button',
				'events': {
					'click': function(e){
					    e = new Event(e).stop();
						report.form.remove();
					}
				},
				'class': 'cancel',
				'value': ' Avbryt '
			}).injectInside(report.fieldset);
			// inject it
			report.form.injectInside(document.body);
		} else {
			$('reportform').setProperty('action',url);
			$('reportform').setStyles({
				'top':pos.y+size.y+'px',
				'left':pos.x+'px'
			});
		}
	},
	/**
	 * Tools.popup(), loads a popup with the given url, width=x and height=y
	 * @param {Object} url (full url or relative path)
	 * @param {Object} x (width of the popup window)
	 * @param {Object} y (height of the popup window)
	 */
	popup: function(url,x,y){
		newWindow = window.open(url,"","width="+x+",height="+y+",left=10,top=10,resizable,scrollbars");
		if (newWindow != null) newWindow.focus();
	},
	/**
	 * 
	 * @param {Object} trackback
	 * @param {Object} error
	 * @param {Object} msg
	 * 
	 * Example: Tools.error("function","No error, just checking","We are experiencing errors, please be patient");
	 */
	error: function(trackback,error,msg){
		new Ajax('errorreport.php',{
			method: 'post', 
			postBody:'error='+msg+'&trackback='+trackback, 
			onComplete: function(r){
				if (r.substr(0,2) == "/*") {
					r = r.substring(2, r.length - 2);
				}
				r = Json.evaluate(r);
				alert("Something something "+ r.ref);
				//
			}
		}).request();
	},
	/**
	 * 
	 * Ping! used to keep the session while in edit mode ;)
	 */	
	/* old ping
	ping: function(){
		var myping = new Ajax('ping.php',{method: 'post',postBody:'console=ping!',onComplete:function(r){
			if(console.log) console.log(r);
		}});
		(function(){
			if(console.log) console.log("Ping!");
			myping.request();
		}).periodical(60000);
	}
	 */
	ping: function(){
		var myping = new Ajax(location.href,{method: 'get',onComplete:function(r){
			if(window.console) console.log('pong!');
		}});
		(function(){
			if(window.console) console.log("Ping!");
			myping.request();
		}).periodical(60000);
	}
}


/**
 * @author Jens Anders Bakke, eddamedia.no
 * "_Events" function collection
 */
var _Events = {
	/**
	 * _Events.croppr()
	 * Adds croppr() events 
	 */
	croppr: function(){
		$$('.croppr').each(function(item){
			item.addEvent('click',function(e){
				// Open Croppr for this image
				if(item.getProperty('rel')){
					myRel = Json.evaluate(item.getProperty('rel'));
					Tools.croppr(myRel.src,myRel.x, myRel.y,myRel.typeid,item);
				} else {
					// error reporting
					Tools.error('croppr','woooi!','huh-haha!');
				}
				//Tools.croppr(item.getProperty('rel'),628, 262);
			});//addEvent
		});//each
		
		if($('cropprloadr')){
			var loadr = $('cropprloadr');
			// Open Croppr for this image
			if(loadr.getProperty('rel')){
				myRel = Json.evaluate(loadr.getProperty('rel'));
				Tools.croppr(myRel.src,myRel.x, myRel.y,myRel.typeid);
			} else {
				// error reporting
				Tools.error('croppr','woooi!','huh-haha!');
			}
		}//if
	},
	/**
	 * 
	 */
	doconfirm: function(){
		$$('.doconfirm').each(function(item){
			item.addEvent('click',function(e){
				if(item.getProperty('rel')){
					msg = item.getProperty('rel');
				} else {
					msg = "Er du sikker på at du vil gjøre det her?"
				}
				if(!Tools.doconfirm(msg)){
					e = new Event(e).stop();
				}
			}); //addEvent
		});//each
	},
	/**
	 * Submit the parent form on click
	 */
	submitonclick: function(){
		$$('.doconfirm a').each(function(item){
			item.addEvent('click',function(e){
				e = new Event(e).stop();
				var _form = $$('form.bluefields')[0];
				if(item.getParent().getProperty('rel')) $('s').value = item.getParent().getProperty('rel');
				_form.setProperty("action",item.getProperty('href'));
				_form.submit();
			}); //addEvent
		});//each
	},
	/**
	 * 
	 */
	mapr: function(){
		$$('.mapup').each(function(item){
			item.addEvent('click',function(e){
				e = new Event(e).stop();
				// do a lightbox with the item.getProperty('href') as iframe url
				myMapr = new Tools.mapr({loader:'iframe',url:item.getProperty('href'),Long:$('f_art_pos_lengdegrad'),Lat:$('f_art_pos_breddegrad')});
			});//addEvent
		});//each
	},
	/* mapr2: function(){
		positionview = [];
		$$('.positionli').each(function(item,i){
			if(!$E('.positionview',item)){
				positionview[i] = new Element('li',{'class': 'positionview'});
				psdl = new Element('dl').injectInside(positionview[i]);
				temp = new Element('dt').setHTML('L:').injectInside(psdl);
				temp = new Element('dd',{'class':'lengdeview'}).setHTML($E('.lengdegrad',item).value).injectInside(psdl);
				temp = new Element('dt').setHTML('B:').injectInside(psdl);
				temp = new Element('dd',{'class':'breddeview'}).setHTML($E('.breddegrad',item).value).injectInside(psdl);
				positionview[i].injectBefore(item);
			}
			$E('.mapup2',item).addEvent('click',function(e){
				e = new Event(e).stop();
				// do a lightbox with the item.getProperty('href') as iframe url
				myMapr = new Tools.mapr({loader:'iframe',url:$E('.mapup2',item).getProperty('href'),Long:$E('.breddegrad',item),Lat:$E('.lengdegrad',item)});
			});//addEvent
			$ES('input',item).each(function(ffe){
				ffe.addEvent('change',function(e){
					//alert($ES('.lengdeview',positionview[i]));
					$ES('.lengdeview',positionview[i]).setHTML($E('.lengdegrad',item).value);
					$ES('.breddeview',positionview[i]).setHTML($E('.breddegrad',item).value);
				});//addEvent
			});//each
			item.setStyle('display','none');
		});//each
	}, */
	mapr2: function(){
		$$('.f_img_details').each(function(item,i){
			$E('.mapup2',item).addEvent('click',function(e){
				e = new Event(e).stop();
				// do a lightbox with the item.getProperty('href') as iframe url
				myMapr = new Tools.mapr({loader:'iframe',url:$E('.mapup2',item).getProperty('href'),Long:$E('.lengdegrad',item),Lat:$E('.breddegrad',item)});
			});//addEvent
		});//each
	},
	/**
	 * Tools.maxcheck(), sets an maximum amount of elements in  an array that can be checked 
	 * @param {Object} items (array of elements to loop through, eg. $('.boxcoloumn input'))
	 * @param {Object} amount (amount of elements that can be checked at a time)
	 * 
	 * Example: _Events.maxcheck($$('.boxcoloumn input'), 3);
	 * 
	 */
	maxcheck: function(containers, amount){
		// make only x numbers of checkboxes selectable at a time
		// $$('.boxcoloumn input').forEach(function(el){
		containers.each(function(item){
			// for each instance of boxcoloumn
			$ES(' input[type="checkbox"]',item).each(function(el){
				el.addEvent('click',function(){
					num = 0;
					$ES(' input[type="checkbox"]', item).each(function(el3){
						if(el3.checked){
							num = 1+num;
						}
					});
					if(num == 1+amount) this.checked = false;
				});
			});
		});
	},
	/**
	 * 
	 */
	onemorefile: function(){
		$$('.onemorefile').forEach(function(item){
			item.addEvent('click',function(e){
				newfile = new Element('input', {
					'type':'file',
					'name':'files[]',
					'class':'file_input'
				});
				
				//imagedesc = new Element('input', {'type':'text','name':'imgtitle[]', 'class':'inputHeight30'});
				//imagedesc2 = new Element('input', {'type':'text','name':'imgdesc[]', 'class':'inputHeight30'});
								
				linebreak = new Element('div', {'style':'clear:left;'});
				
				//item.getParent().appendChild(newfile);
				//item.getParent().appendChild(imagedesc);
				//item.getParent().appendChild(imagedesc2);
				//item.getParent().appendChild(linebreak);
				
				newfile.injectBefore($('imgupnb'));
				//imagedesc.injectBefore($('imgupnb'));
				//imagedesc2.injectBefore($('imgupnb'));
				linebreak.injectBefore($('imgupnb'));
				
				e = new Event(e).stop();
			});
		});
	},
	onoff: function(){
		$$('.onoff').forEach(function(item){
			item.addEvent('click',function(e){
				e = new Event(e).stop();
				myParent = item.getParent();
				// if the current state was off
				if(myParent.hasClass("off")){
					myParent.addClass("on");
					myParent.removeClass("off");
					if($('f_advanced')) $('f_advanced').value="on";
				
				// if it's not, it was on
				}else{
					myParent.addClass("off");
					myParent.removeClass("on");
					if($('f_advanced')) $('f_advanced').value="off";
				}
			
			});
		});
	},
	reportthis: function(){
		$$('.rapporter a, a.rapporter').each(function(item){
			if(item.getProperty("rel")){
				item.addEvent('click',function(e){
					e = new Event(e).stop();
					Tools.addreport(item.getProperty('href'),item.getProperty('rel'),item);
				});
			}
		});
		$$('#videoupload').each(function(item){
			item.addEvent('submit',function(e){
				var overlay = new Element('div',{
					'class':'uploaderoverlay'
				}).setHTML('<p>Vennligst vent mens videofilen lastes opp. Dette kan ta litt tid, avhengig av størrelsen på filen.</p>').injectInside($E('#videoupload fieldset'));
			});
		});
	}
}

//if(!window.ie) window.addEvent('domready', function(){Site.start();});