//Some from kichimi :)

function ShowAdminBar(imgid){
	gID('ab_'+imgid).style.visibility = 'visible'; 
}

function HideAdminBar(imgid){
	gID('ab_'+imgid).style.visibility = 'hidden'; 
}


// More from Dug
function highlight(that) {
	that.focus();
	that.select();
}
function unhighlight(that) {
	that.value=that.value;
}

function derp() {
    if (window.XMLHttpRequest) {
	http_request = new XMLHttpRequest();
	if (http_request.overrideMimeType) { http_request.overrideMimeType('text/html'); }
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
		try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	//http_request.onreadystatechange = alertContents;
	http_request.open('GET', "/derplog", true);
	http_request.send(null);

    gID('derpsound').play();
	setTimeout('window.top.location="/";', 1800);
	return false;
}

function vote(pid,vid) {
	var res,ans;
    if (window.XMLHttpRequest) {
	http_request = new XMLHttpRequest();
	if (http_request.overrideMimeType) { http_request.overrideMimeType('text/html'); }
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
		try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	//http_request.onreadystatechange = alertContents;
	http_request.open('GET', "/vote?ajax=1&pid=" + pid + "&vid=" + vid, true);
	http_request.onreadystatechange = function(){
		if (http_request.readyState == 4) {
			if (http_request.status!=200) {
				if (http_request.responseText) { alert("Sorry, your vote was not allowed.\n\nReason: "+http_request.responseText); }
			} else {
				ans=http_request.responseText;
				res=ans.split(",");;
				gID("voteup").innerHTML=res[0];
				gID("votedown").innerHTML=res[1];
				gID("voteresult").innerHTML=(res[0]-res[1]);
			}
		}
	};

	http_request.send(null);
	return false;
}

function uploadURL(url) {
	gID("recentfiles").style.display="none";
	gID("uploadqueue").style.display="block";
	var xmlHttpReq = false;
	var self = this;
	if (window.XMLHttpRequest) { self.xmlHttpReq = new XMLHttpRequest(); } else if (window.ActiveXObject) { self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); }
	self.xmlHttpReq.open('POST', "/upload", true);
	self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	self.xmlHttpReq.onreadystatechange = function() {
	if (self.xmlHttpReq.readyState == 4) {
		response=self.xmlHttpReq.responseText;
		if (self.xmlHttpReq.status==200) {
			var tbody = gID("uploads").getElementsByTagName("TBODY")[0];
			tbody.innerHTML=tbody.innerHTML+('<tr><td align="center"><img src="/' + response + '.small" height="100"></td><td><b>URLs</b><br /><a href="' + domain2 + response + '">' + domain2 + response + '</a><br /><input type="text" value="' + domain2 + response + '" class="uploadurl" size="25" onclick="this.focus();this.select();" /><br /><br /><b>Statistics:</b> <a href="' + domain + response + '.info">' + domain + response + '.info</a></td></tr>')
			uploadedcount++;
			gID('uploaded').innerHTML=uploadedcount;
		} else {
			alert("Invalid URL\n" + self.xmlHttpReq.responseText);
		}
	}}
	self.xmlHttpReq.send("url=" + escape(url) + "&folder=" + codes + "&return=0");
}

function shortenURL(url) {
	gID("recentfiles").style.display="none";
	gID("uploadqueue").style.display="block";
	var xmlHttpReq = false;
	var self = this;
	if (window.XMLHttpRequest) { self.xmlHttpReq = new XMLHttpRequest(); } else if (window.ActiveXObject) { self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); }
	self.xmlHttpReq.open('POST', "/upload", true);
	self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	self.xmlHttpReq.onreadystatechange = function() {
	if (self.xmlHttpReq.readyState == 4) {
		response=self.xmlHttpReq.responseText;
		if (self.xmlHttpReq.status==200) {
			var tbody = gID("uploads").getElementsByTagName("TBODY")[0];
			tbody.innerHTML=tbody.innerHTML+('<tr><td align="center"><img src="/' + response + '.small" height="100"></td><td><b>URLs</b><br /><a href="' + domain2 + response + '">' + domain2 + response + '</a><br /><input type="text" value="' + domain2 + response + '" class="uploadurl" size="25" onclick="this.focus();this.select();" /><br /><br /><b>Statistics:</b> <a href="' + domain + response + '.info">' + domain + response + '.info</a></td></tr>')
			uploadedcount++;
			gID('uploaded').innerHTML=uploadedcount;
		} else {
			alert("Invalid URL\n" + self.xmlHttpReq.responseText);
		}
	}}
	self.xmlHttpReq.send("u=" + escape(url) + "&folder=" + codes + "&return=0");
}

/* google goodness */
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-18880990-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
  
// SUPA //
	var clipboardapploaded=0;
	function loadapplet() {
		if (clipboardapploaded==0) {
			gID("clipboardapplet").innerHTML = '<applet id="SupaApplet" archive="/site/supa.jar" code="de.christophlinder.supa.SupaApplet" width="200" height="200"><param name="imagecodec" value="jpg"><param name="encoding" value="base64"><param name="previewscaler" value="fit to canvas">Please install Java</applet>';
			clipboardapploaded=1;
		}
	}

    function paste() {
	  gID("recentfiles").style.display="none";
	  gID("uploadqueue").style.display="block";
      loadapplet();
      var s = new supa();
      // Call the paste() method of the applet.
      // This will paste the image from the clipboard into the applet :)
      try {
        var applet = gID( "SupaApplet" );

        if( !s.ping( applet ) ) {
          throw "Java applet didn't load.\n\nDo you have Java installed and enabled?";
        }

        var err = applet.pasteFromClipboard(); 
        switch( err ) {
          case 0:
            /* no error */
            break;
          case 1: 
            alert( "Unknown Error" );
            break;
          case 2:
            alert( "Empty clipboard" );
            break;
          case 3:
            alert( "Clipboard content not supported. Only image data is supported." );
            break;
          case 4:
            alert( "Clipboard in use by another application. Please try again in a few seconds." );
            break;
          default:
            alert( "Unknown error code: "+err );
        }
      } catch( e ) {
        alert(e);
        throw e;
      }

      return false;
    }

    function upload() {
      loadapplet();
      // Get the base64 encoded data from the applet and POST it via an AJAX 
      // request. See the included Supa.js for details
      var s = new supa();
      var applet = gID( "SupaApplet" );

      try { 
        var result = s.ajax_post( 
          applet,       // applet reference
          "upload", // call this url
          "screenshot", // this is the name of the POSTed file-element
          "clipboard.jpg", // this is the filename of tthe POSTed file
          { form: document.forms["form"] } // elements of this form will get POSTed, too
        );
        if( result.match( "^OK" ) ) {
          var url = result.substr( 3 );
          window.open( url, "_blank" );
        } else {
			var tbody = gID("uploads").getElementsByTagName("TBODY")[0];
			tbody.innerHTML=tbody.innerHTML+('<tr><td align="center"><img src="/' + result + '.small" height="100"></td><td><b>URLs</b><br /><a href="' + domain2 + result + '">' + domain2 + result + '</a><br /><input type="text" value="' + domain2 + result + '" class="uploadurl" size="25" onclick="this.focus();this.select();" /><br /><br /><b>Statistics:</b> <a href="' + domain + result + '.info">' + domain + result + '.info</a></td></tr>')
			uploadedcount++;
			gID('uploaded').innerHTML=uploadedcount;
		}

      } catch( ex ) {
        if( ex == "no_data_found" ) {
          if (paste()) {  upload(); }
        } else {
			alert(ex);
        }
      }

      return false; // prevent changing the page
    }

	//vim :set tabstop=2 shiftwidth=2 expandtab
/*
 *    I am placing this code in the Public Domain. Do with it as you will.
 *    This software comes with no guarantees or warranties but with
 *    plenty of well-wishing instead!
 */

// This piece of code's sole purpose is providing a small demo app for SUPA.
// Please do not use this as a reference for your implementation 
// as good coding style was left out for simplicitys sake!

// Dug - shh, don't be a wimp

function supa() {
  this.ping = function( supaApplet ) {
    try {
      // IE will throw an exception if you try to access the method in a 
      // scalar context, i.e. if( supaApplet.pasteFromClipboard ) ...
      return supaApplet.ping();
    } catch( e ) {
      return false;
    }
  }

  this.ajax_post = function(  supaApplet, 
                              actionUrl, 
                              fieldname_filename, 
                              filename, 
                              otherParams ) 
  {
    // sanity checks
    if( !fieldname_filename || fieldname_filename == "" ) {
      throw "Developer Error: fieldname_filename not set or empty";
    }

    if( !filename || filename == "" ) {
      throw "Filename required";
    }


    if( !this.ping( supaApplet ) ) {
      throw "SupaApplet is not loaded (yet)";
    }

    // get bytes from the applet
    var bytes = supaApplet.getEncodedString();
    if( !bytes || bytes.length == 0 ) {
      // we're optimistic: any exception means: there's no data :)
      throw "no_data_found";
    }
    //alert( "bytes: "+bytes.length );

    // some constants for the request body
    //FIXME: make sure boundaryString is not part of bytes or the form values
    var boundaryString = 'AaB03x'+ parseInt(Math.random()*9999999,10); 
    var boundary = '--'+boundaryString;
    var cr= '\r\n';

    // build request body
    var body = '';
    body += boundary + cr;

    // add "normal" form values
    if( otherParams && otherParams.form ) {
      for( var i = 0; i < otherParams.form.elements.length; ++i ) {
        var elem = otherParams.form.elements[i];
        if( elem.name ) {
          //alert( elem.name );
          //FIXME: is this the correct encoding?
          body += "Content-disposition: form-data; name=\""+escape(elem.name)+"\";" + cr;
          body += cr;
          body += encodeURI(elem.value) + cr;
          body += boundary + cr;
        }
      }
    }
    if( otherParams && otherParams.params ) {
      for( var key in otherParams.params ) {
          body += "Content-disposition: form-data; name=\""+escape(key)+"\";" + cr;
          body += cr;
          body += encodeURI(otherParams.params[key]) + cr;
          body += boundary + cr;

      }
    }


    // add the screenshot as a file
    //FIXME: is this the correct encoding?
    body += "Content-Disposition: form-data; name=\""+escape(fieldname_filename)+"\"; filename=\""+encodeURI(filename)+"\"" + cr;
    body += "Content-Type: application/octet-stream" + cr;
    body += "Content-Transfer-Encoding: base64" + cr;
    body += cr;
    body += bytes + cr;
    // last boundary, no extra cr here!
    body += boundary + "--" + cr;

    // finally, the Ajax request
    var isAsync = false;
    var xrequest = new XMLHttpRequest();
    xrequest.open( "POST", actionUrl, isAsync );

    // set request headers
    // please note: chromium nees charset set explicitly.
    //   It will autocomplete if it's missing but it won't work 
    //   (PHP backend only)?
    // also: chromium considers setting Content-length and Connection unsafe
    // this is no problem as all browsers seem to determine this automagically.
    xrequest.setRequestHeader( "Content-Type", "multipart/form-data; charset=UTF-8; boundary="+boundaryString );
    //xrequest.setRequestHeader( "Content-length", body.length );
    //xrequest.setRequestHeader( "Connection", "close" );
    xrequest.send( body );

    return xrequest.responseText;
  }
}

/*
	* Konami-JS ~ 
	* :: Now with support for touch events and multiple instances for 
	* :: those situations that call for multiple easter eggs!
	* Code: http://konami-js.googlecode.com/
	* Examples: http://www.snaptortoise.com/konami-js
	* Copyright (c) 2009 George Mandis (georgemandis.com, snaptortoise.com)
	* Version: 1.3.2 (7/02/2010)
	* Licensed under the GNU General Public License v3
	* http://www.gnu.org/copyleft/gpl.html
	* Tested in: Safari 4+, Google Chrome 4+, Firefox 3+, IE7+ and Mobile Safari 2.2.1
*/

var Konami = function() {
	var konami= {
			addEvent:function ( obj, type, fn, ref_obj )
			{
				if (obj.addEventListener)
					obj.addEventListener( type, fn, false );
				else if (obj.attachEvent)
				{
					// IE
					obj["e"+type+fn] = fn;
					obj[type+fn] = function() { obj["e"+type+fn]( window.event,ref_obj ); }
	
					obj.attachEvent( "on"+type, obj[type+fn] );
				}
			},
	        input:"",
	        pattern:"3838404037393739666513",
		/*pattern:"38384040373937396665",*/
	        load: function(link) {	
				
				this.addEvent(document,"keydown", function(e,ref_obj) {											
					if (ref_obj) konami = ref_obj; // IE
					konami.input+= e ? e.keyCode : event.keyCode;
					if (konami.input.length > konami.pattern.length) konami.input = konami.input.substr((konami.input.length - konami.pattern.length));
					if (konami.input == konami.pattern) {
                    konami.code(link);
					konami.input="";
                   	return;
                    }
            	},this);
           this.iphone.load(link)
	                
				},
	        code: function(link) { window.location=link},
	        iphone:{
	                start_x:0,
	                start_y:0,
	                stop_x:0,
	                stop_y:0,
	                tap:false,
	                capture:false,
									orig_keys:"",
	                keys:["UP","UP","DOWN","DOWN","LEFT","RIGHT","LEFT","RIGHT","TAP","TAP","TAP"],
	                code: function(link) { konami.code(link);},
	                load: function(link){
										orig_keys = this.keys;
	    							konami.addEvent(document,"touchmove",function(e){
	                          if(e.touches.length == 1 && konami.iphone.capture==true){ 
	                            var touch = e.touches[0]; 
	                                konami.iphone.stop_x = touch.pageX;
	                                konami.iphone.stop_y = touch.pageY;
	                                konami.iphone.tap = false; 
	                                konami.iphone.capture=false;
	                                konami.iphone.check_direction();
	                                }
	                                });               
	                        konami.addEvent(document,"touchend",function(evt){
	                                if (konami.iphone.tap==true) konami.iphone.check_direction(link);           
	                                },false);
	                        konami.addEvent(document,"touchstart", function(evt){
	                                konami.iphone.start_x = evt.changedTouches[0].pageX
	                                konami.iphone.start_y = evt.changedTouches[0].pageY
	                                konami.iphone.tap = true
	                                konami.iphone.capture = true
	                                });               
	                                },
	                check_direction: function(link){
	                        x_magnitude = Math.abs(this.start_x-this.stop_x)
	                        y_magnitude = Math.abs(this.start_y-this.stop_y)
	                        x = ((this.start_x-this.stop_x) < 0) ? "RIGHT" : "LEFT";
	                        y = ((this.start_y-this.stop_y) < 0) ? "DOWN" : "UP";
	                        result = (x_magnitude > y_magnitude) ? x : y;
	                        result = (this.tap==true) ? "TAP" : result;                     

	                        if (result==this.keys[0]) this.keys = this.keys.slice(1,this.keys.length)
	                        if (this.keys.length==0) { 
														this.keys=this.orig_keys;
														this.code(link)
														}
	                        }
	                }
	}
	return konami;
}

konami = new Konami();
konami.load("/derp");

function fadeResi(id,pc) {
	try {
		gID("resi" + id).style.filters.alpha.opacity=pc;
	} catch (e) {
		try {
			gID("resi" + id).style.MozOpacity=(pc/100);
		} catch(e) { }
	}
}

function ajaxDelete(id) {
	if (confirm('Are you sure you want to delete this?')) {
		fadeResi(id,50);
		if (window.XMLHttpRequest) {
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) { http_request.overrideMimeType('text/html'); }
		} else if (window.ActiveXObject) { // IE
			try {
				http_request = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
			try {
					http_request = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {}
			}
		}
		//http_request.onreadystatechange = alertContents;
		http_request.open('GET', "/delete?ajax=1&id=" + id, true);
		http_request.onreadystatechange = function(){
			if (http_request.readyState == 4) {
				if ((http_request.status!=200) && (http_request.status!=301) && (http_request.status!=302)) {
					if (http_request.responseText) { alert("Sorry, that was not allowed.\n\nReason: "+http_request.responseText); }
				} else {
					gID("resi" + id).style.display="none";
				}
			}
		};

		http_request.send(null);
		return false;
	} else {
		return false;
	}
}
function ajaxFavourite(id) {
	if (confirm('Are you sure you want to favourite this?')) {
		fadeResi(id,80);
		if (window.XMLHttpRequest) {
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) { http_request.overrideMimeType('text/html'); }
		} else if (window.ActiveXObject) { // IE
			try {
				http_request = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
			try {
					http_request = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {}
			}
		}
		//http_request.onreadystatechange = alertContents;
		http_request.open('GET', "/ajax/facebookfeatured.php?ajax=1&id=" + id, true);
		http_request.onreadystatechange = function(){
			if (http_request.readyState == 4) {
				if ((http_request.status!=200) && (http_request.status!=301) && (http_request.status!=302)) {
					if (http_request.responseText) { alert("Sorry, that was not allowed.\n\nReason: "+http_request.responseText); }
				} else {
					fadeResi(id,100);
				}
			}
		};

		http_request.send(null);
		return false;
	} else {
		return false;
	}
}

function gID(i) { return document.getElementById(i); }

function sfwidiotcheck() {
	if(!gID('sfc').checked && !gID('sfw').checked && !gID('nsfw').checked && !gID('nsfa').checked && !gID('unm').checked){
		alert('Please select at least one type of image to view');
		return false;
	} else {
		return true;
	}
}

function sfwidiotcheckhead() {
	if(!gID('sfch').checked && !gID('sfwh').checked && !gID('nsfwh').checked && !gID('nsfah').checked && !gID('unmh').checked){
		alert('Please select at least one type of image to view');
		return false;
	} else {
		return true;
	}
}

function showhideSFWmenu() {
	$('#sfwmenu').slideToggle('slow');
	return false;
}
