function $(){
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}

var elembyid = $;

function hide() {
	for (var i = 0; i < arguments.length; i++) {
		var e = $(arguments[i]);
		if (e)
			e.style.display = "none";
	}
}

function show() {
	for (var i = 0; i < arguments.length; i++) {
		var e = $(arguments[i]);
		if (e)
			e.style.display = "";
	}
}

function toggle_visibility(elem) {
	var e = $(elem);
	if (e) {
		if (e.style.display == "none") {
			e.style.display = "";
			return true;
		} else {
			e.style.display = "none";
			return false;
		}
	}
	return false;
}

function selectResolution()
{
	var sel = document.resolutionForm.res;
	if (sel && firstLoad)
	{
		fistLoad = false;
		var res = screen.width+'x'+screen.height;
		for(i=0;i<sel.options.length;i++)
		{
			if (sel.options[i].text == res)
			{
				//sel.value = i;
				sel.options[i].selected = true;
				break;
			}
		}
	}
}

/*
 * AJAX functions.
 */

/* IE */
var xmlHttp = false;
try {
	xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
	try {
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	} catch (e2) {
		xmlHttp = false;
	}
}
if (typeof(xmlHttp)=='boolean')
	xmlHttp = new XMLHttpRequest();

function makecb(f) {
	function cb() {
		if (xmlHttp.readyState == 4) {
			//hide("loading");
			var response = xmlHttp.responseText.parseJSON();
			//$("reply").value = response.toJSONString();
			if (response != "ERROR" && xmlHttp.status == 200) {
				f(response)
			} else {
				/* TODO: find a better way to report errors */
				/*alert("Error completing operation: " +
					response.toJSONString());*/
			}
		}
	}
	return cb;
}

function request(callback, url) {
	xmlHttp.open("GET", url, true);
	xmlHttp.onreadystatechange = makecb(callback);
	//show("loading");
	xmlHttp.send(null);
}

/* Ajax stuff */
function makepp(id,type)
{
	request(makeppcb,'/make/' + type + '/' + id);
}

function makeppcb(resp)
{
	if (resp)
	{
		id = parseInt(resp[0]);
		if (resp[1]=='1')
		{
			type = 'private';
			ctype = 'public';
		}
		else
		{
			type = 'public';
			ctype = 'private';
		}
		$('make'+type+id).className='';
		$('make'+ctype+id).className='toggleopacity';
	}
}

function fav(id) 
{
	request(favcb,'/fav?id=' + id);
}

function unfav(id)
{
	request(favcb,'/fav?un=1&id=' + id);
}

function favcb(resp)
{
	if (resp)
	{
		resp = resp.split(' ');
		var myr = parseInt(resp[2]);
		var id = parseInt(resp[0]);
		if ($('showrank'+id))
		{
			$('showrank'+id).innerHTML='votes all: ' + resp[1] + ' my: ' + myr;
		} else if ($('showallrank'+id))
		{
			$('showallrank'+id).innerHTML=resp[1];
		}
		if (myr>=1)
		{
			$('rankup'+id).className='';
			$('rankdown'+id).className='toggleopacity';
		} else if (myr<=-1)
		{
			$('rankdown'+id).className='';
			$('rankup'+id).className='toggleopacity';
		} else {
			$('rankup'+id).className='toggleopacity';
			$('rankdown'+id).className='toggleopacity';
		}
		
	}	
	//checkMoveUp(resp[0]);
	//hide('showrank'+resp[0]);
}

function delcb(resp){}

function getParent(obj)
{
	if (obj.parentNode) y = obj.parentNode;
	else if (obj.parentElement) y = obj.parentElement;
	else return;
	return y;
}

function checkMoveUp(id)
{
	var mc = $('maincontainer');
	var x = mc.getElementsByTagName('div');
	var lasteltid = null;
	for (var i=0;i<x.length;i++)
	{
		if (x[i].id.length>0 && x[i].id[0]=='t')
			if (x[i].id.substring(5)==id)
				break;
			else
				lasteltid = x[i].id.substring(5);
	}

	if (lasteltid!=null)
	{
		var lfavs = parseInt($('showrank' + lasteltid).innerHTML.substring(5));
		var cfavs = parseInt($('showrank' + id).innerHTML.substring(5));
		
		//alert(lfavs + ' ' + cfavs);
		if (lfavs<cfavs)
		{
			x1 = $('thumb'+lasteltid);
			x2 = $('thumb'+id);
			p1 = getParent(x1);
			p2 = getParent(x2);
			var tmp = p1.innerHTML;
			p1.innerHTML = p2.innerHTML;
			p2.innerHTML = tmp;
		}
	}
}

function edit_collections(type,id,collections) 
{
	s = '/edit_collections/' + type + '/' + id + '/' + collections;
	request(edit_collectionscb,s);
}

function edit_collectionscb(resp)
{
	if (resp)
	{
		$('collections').innerHTML = resp;
	}
}

function addcollections(id,colname)
{
    if (colname=='')
		colname = elembyid('editcollectionsinput').value;
		
	edit_collections('add',id,colname);
	hide('editcollections');
	show('addtocollections');
}

function delete_collection(id,name)
{
	edit_collections('del',id,name);
}

function select_add_collections()
{
	show('editcollections');
	hide('addtocollections');
	elembyid('editcollectionsinput').focus();
	elembyid('editcollectionsinput').select()
}

function viewcollection()
{
	var x = $('collection');
	if (x.value)
	{
		if (x.isFocused)
			document.location.href='/collection/'+encodeURIComponent(x.value)
		else
			x.focus();
	}
	else
	{
		show('collection');
		x.focus();
	}
}

function addfromfile()
{
	show('file'); hide('url'); elembyid('file').focus(); document.mainform.choosetype[0].checked=true;
}

function addfromurl()
{
	show('url'); hide('file'); elembyid('url').focus(); document.mainform.choosetype[1].checked=true;
}

function addfromfile_home()
{
	elembyid('file').focus(); document.mainform.choosetype[0].checked=true;
}

function addfromurl_home()
{
	elembyid('url').focus(); document.mainform.choosetype[1].checked=true;
}

function change_name(id) 
{
	hide('picturenameedit','achangename');
	show('picturename');

	name = elembyid('picturenameedit').value;
	s = '/change_name?id=' + id + '&name=' + encodeURIComponent(name);
	request(change_namecb,s);
}

function change_namecb(resp)
{
	$('picturename').innerHTML=resp;
}

function getViewport()
{
	var viewport = {x:0,y:0,width:0,height:0};
	
	if (typeof window.scrollX != 'undefined')
	{
	viewport.x = window.pageXOffset;
	viewport.y = window.pageYOffset;
	viewport.width = window.innerWidth;
	viewport.height = window.innerHeight;
	return viewport;
	}
	else
	{
	if (document.documentElement &&
	(typeof document.documentElement.scrollLeft != 'undefined') &&
	(document.documentElement.scrollLeft != 0))
	{
	viewport.x = document.documentElement.scrollLeft;
	viewport.y = document.documentElement.scrollTop;
	viewport.width = document.documentElement.clientWidth;
	viewport.height = document.documentElement.clientHeight;
	return viewport;
	}
	else
	{
	if (document.body &&
	(typeof document.body.scrollLeft != 'undefined'))
	{
		viewport.x = document.body.scrollLeft;
		viewport.y = document.body.scrollTop;
		
		if (document.compatMode == "CSS1Compat")
		{
			viewport.width = document.body.parentNode.clientWidth;
			viewport.height = document.body.parentNode.clientHeight;
		}
		else
		{
			viewport.width = document.body.clientWidth
			viewport.height = document.body.clientHeight;
		}
		
		return viewport;
	}
	}
	}
	
	return null;
}

function showlogin(loc)
{
	show('cover', 'loginpopup');
	if ($('res'))
		$('res').style.visibility='hidden';
	var vp = getViewport();
	$('cover').style.width = vp.width + 'px';
	$('loginpopup').style.top = (vp.y + screen.height/2 - 200) + 'px';
	elembyid('input_user').focus(); 
	if (document.loginform)
		document.loginform.currenturl.value=loc;
	return false;
}

function favorlogin(id,user,up)
{
	if (user)
		if (up)
			fav(id);
		else
			unfav(id);
	else
		showlogin('/resize-image/' + id);
}

function showbigimage(url,w,h)
{
	show('loading_details');
	if  ($('bigimagecover_details').getElementsByTagName('img').length==1)
	{
		var vp = getViewport();
		var newimg=document.createElement('img');

		if (vp.width-50>=w)
		{
			newimg.style.left = Math.floor(vp.width/2)+'px';
			newimg.style.marginLeft = -Math.floor(w/2)+'px';
		}
		else
			newimg.style.left = '0px';

		newimg.className = 'cover';
		newimg.onload = (function() { newimg.className = 'coverloaded'; show('closeimg_details'); hide('loading_details'); });
		newimg.src=url;
		
		$('loading_details').style.left = Math.floor(vp.width/2) + 'px';
		$('loading_details').style.top = Math.floor(vp.height/2) + 'px';
		$('loadingtext_details').style.left = Math.floor(vp.width/2) - 75 + 'px';
	    $('loadingtext_details').style.top = Math.floor(vp.height/2) - 50 + 'px';

		var mt = (vp.height-h)/2;
		if (mt>0) newimg.style.marginTop = mt+'px';
		$('bigimagecover_details').appendChild(newimg);
		
		var closeimg = $('closeimg_details');
		closeimg.style.marginTop = newimg.style.marginTop;

		if (newimg.style.left!='0px')
		{
			closeimg.style.left = newimg.style.left;
			closeimg.style.marginLeft = Math.floor(w/2)+3+'px';
		} else {
			closeimg.style.color = "#d33";
		}
		
		h = 2000;
		$('bigimagecover_details').style.height = h+'px';
		$('bigimagecover_details').style.width = vp.width+'px';
    } else {
		show('closeimg_details'); 
		hide('loading_details');
	}

	$('res').style.visibility='hidden';        
	$('denoise').style.visibility='hidden';
	$('smooth').style.visibility='hidden';
	show('bigimagecover_details');
}

function showbigimage_index(id,w,h)
{
	show('loading');
	if  ($('bigimagecover').getElementsByTagName('img').length==2)
	{
    	$('bigimagecover').removeChild($('bigimagecover').getElementsByTagName('img')[1]);
	}
	
	var vp = getViewport();
	var y = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;	
 
	var newimg=document.createElement('img');
	var nw, nh;
		
	if (typeof(id)=='number')
	{
		if (w>600 || h>600)
		{
			if (w>h)
			{
				nw = 600;
				nh = h/w*600;
			}
			else
			{
				nw = w/h*600;
				nh = 600;
			}
		} else {
			nw = w;
			nh = h;
		}
	} else {
		nw = w;
		nh = h;
	}

	newimg.style.left = Math.floor(vp.width/2)+'px';
	newimg.style.marginLeft = -Math.floor(nw/2)+'px';
	newimg.style.top = y + Math.floor(vp.height/2 - nh/2) + 'px';

	newimg.className = 'cover';
	newimg.onload = (function () {
		newimg.className = 'coverloaded'; 		
		var closeimg = $('closeimg');
		closeimg.style.top = y + Math.floor(vp.height/2 - nh/2) - 3 + 'px';
		closeimg.style.left = newimg.style.left;
		closeimg.style.marginLeft = (Math.floor(nw/2)+1)+'px';	
		show('closeimg');
		hide('loading');
	});

	if (typeof(id)=='number')
		newimg.src='/picture/medium/' + id + '.jpg';
	else
		newimg.src = id;

	$('loading').style.left = Math.floor(vp.width/2)+'px';
	$('loading').style.top = Math.floor(vp.height/2) + y +'px';
	$('loadingtext').style.left = Math.floor(vp.width/2) - 75 +'px';
	$('loadingtext').style.top = Math.floor(vp.height/2) - 50 + y +'px';

	$('bigimagecover').appendChild(newimg);
	$('bigimagecover').style.height = 10000+'px';
	$('bigimagecover').style.width = vp.width+'px';

	show('bigimagecover');
}

function vhide(elt)
{
	$(elt).style.visibility='hidden';
}
function vshow(elt)
{
	$(elt).style.visibility='visible';
}

function zoom_mouseout(id)
{
	hide('zoom'+id);show('thumb'+id);
}

function thumb_mouseover(id)
{
	hide('thumb'+id);show('zoom'+id);
}

function selectcollection(state, cname)
{
	parts = state.split(' ');
	return parts[0] + cname + parts[1];
}

function getElementsByName_iefix(tag, name) {
     
     var elem = document.getElementsByTagName(tag);
     var arr = new Array();
     for(i = 0,iarr = 0; i < elem.length; i++) {
          att = elem[i].getAttribute("name");
          if(att == name) {
               arr[iarr] = elem[i];
               iarr++;
          }
     }
     return arr;
}

function selectPlacement4Res()
{
	var thumbs = document.getElementsByName('thumbframe');
	if (typeof(thumbs[0])=='undefined')
		thumbs = getElementsByName_iefix('div','thumbframe');
	
	var vp = getViewport();
	var w = vp.width;
	for (var i = 0; i<thumbs.length; i++)
	{
		if (w<800)
		{
			thumbs[i].style.width = '48%';
		} else if (w<1200)
		{
			thumbs[i].style.width = '31.5%';
		} else
			thumbs[i].style.width = '23.5%';
	}
}

var did_submit=-1;
function addSubmit()
{
	if (did_submit==0 && (document.mainform.file.value!='' || document.mainform.url.value!='')) 
	{
		show('submitting');
		document.mainform.submit(); 
		did_submit=1;
		return true;
	} else {
		return false;
	}
}

function getResizeUrl()
{
	var f = document.resolutionForm,
		cx = f.crop_x.value,
		cy = f.crop_y.value;
		
	cx = cx>0?cx:0;
	cy = cy>0?cy:0;
	
	url =    '/resize' + 
			(f.crop.checked?('/crop-' + cx + '-' + cy + '-' + f.crop_width.value + '-' + f.crop_height.value): '') +
			(f.constrain.checked?'/constrain':'') +
			(f.stretch.checked?'/stretch':'') +
			(f.centercrop && f.centercrop.checked?'/centercrop':'') +
			(f.smoothcheck.checked?'/smooth-'+f.smooth.value:'')+
			(f.denoisecheck.checked?'/denoise-'+f.denoise.value:'')+		
			'/image-' + f.id.value + '-' + f.res.value;
	//alert(url);
	return url;
}

function go_image(url)
{
	img = new Image(); 
	img.src=url;
	img.onload=(function() {document.location.href = url;});
}

function showSubmitting() {
	elembyid("submitting").innerHTML = '<img src="/static/images/loading.gif" alt="submitting ..." border="0">';
}

function doResizeImage()
{
	show('submitting'); 
	document.location.href='/resized-image/'+getResizeUrl();
	return true;
}

var errMsgs = ['To enable more than 200% zoom resizes make sure: <ul><li>you are logged in with your reshade user account</li><li>you have enough credits to use: <a href="/online-image-resizer/buy-credits">buy credits here</a>!</li></ul>',
			   'The selected image size is too small, please make a larger crop or choose a smaller resolution.',
			   'You cannot crop an image if you are not logged in. Please <a href="" onClick="showlogin(); return false;">log in</a> first.'];
			   
function showResizedImage(url,credits)
{
	var url_parts = url.split('-'),
		res = url_parts[url_parts.length-1],
		ress = res.split('x'), estimatedTime = 0,
		timePerOp = 4e-6;
	if (ress.length==2)
		estimatedTime = Math.ceil(ress[0]*ress[1]*timePerOp);

	if (estimatedTime>1)
		$('timeEstimate').innerHTML = estimatedTime;

	var im = $('resizedimage');
	var ow, oh;
	
	function showResizedImageOnLoad()
	{
		show('resizedimage_div');
		var browserName=navigator.appName;		
		var imwidth =  (browserName == "Netscape" || navigator.userAgent.indexOf("MSIE 8") != -1)?im.width:im.width-20;
		if (imwidth<5)
		{
			hide('resizedimage_div');
			hide('pleasewait'); 
			show('goback');
			show('errordiv');
			var i =imwidth-1, msg;
			
			if (i<errMsgs.length)
			{
				msg = errMsgs[i];
			}
			else
			{
				msg = 'An unknown error has occured. Please try again.'
			}

			$('errordiv').innerHTML = msg;
		} else {
			hide('pleasewait');
			$('resizedimage_container').className='resizedimage';
			var w = im.width, h = im.height;
			ow = w; oh = h;
			if (browserName != "Netscape")
			{
				w -= 20;
				h -= 20;
			}
			$('showresized').innerHTML = w + 'x' + h;
			
			if (!(ow<screen.width && oh<screen.height) && (browserName == "Netscape"))
				im.style.cursor = 'all-scroll';
				
			if (credits<1)
				show('buycredits');
				
			if (location.href.indexOf('/crop-')==-1)
			{
				var resizeLink = 'http://reshade.com/' + location.href.split('//')[2],
					imgLink = 'http://reshade.com/resize-image/' + location.href.split('/image-')[1].split('-')[0];
				$('htmllink').value = $('textareaWildfire').value = "<a target='_blank' href='" + imgLink + "'><img src='" + resizeLink + "' border='0'/></a>";
				$('directlink').value = resizeLink;
				$('forumlink').value = "[URL=" + imgLink + "][IMG]" + resizeLink + "[/IMG][/URL]";
				$('altforumlink').value = "[URL=" + imgLink + "][IMG=" + resizeLink + "][/URL]";			
				$('instamesslink').value = imgLink;
				show('linksbox');
			}
		}
	}
	
	function incorrectParams()
	{
		hide('pleasewait'); 
		show('goback');
		show('errordiv');
		$('errordiv').innerHTML = 'There was an error resizing the image. Please check the settings and try again.';
	}
	
	var shrinked = false;
	function onClickShrinkRestore()
	{
		var rw = ow/(screen.width-100),
		    rh = oh/(screen.height-200),
		    r = rw>rh?rw:rh;
		if (!shrinked) //original
		{
			if (r>1)
			{
				im.width=ow/r;
				im.height=oh/r;
			}
		} else {
			im.width = ow;
			im.height = oh;
		}
		shrinked=!shrinked;
	}
	
	im.onload = showResizedImageOnLoad;
	im.onerror = incorrectParams;
	im.src = url;
	if (navigator.appName == "Netscape")
		im.onclick = onClickShrinkRestore;
}

function getPollUrl(url)
{
	request((function(){}),url);
	$('pollquestion').innerHTML = 'Thank you! Your feeback is greatly appreciated'
}

function zoomCenterCrop(nw,nh,w,h)
{
	if (nw/w > nh/h) 
	{
		return nw/w;
	}
	else
	{
		return nh/h;
	}
}

function gettip(id,cat) 
{
	request(gettipcb,'/gettip/' + id + '/' + cat);
}

function gettipcb(r)
{
	$('details_tip').innerHTML = r;
}
