/* Turn a dropdown selector into buttons which look like toggle switches
---------------------------------------------- */

function toggleSwitch(selector)
{
	//hide dropdown
	$(selector).hide();

	$(selector).each(function(){
		//start buffer
		var buffer = '<span class="buttongroup toggleSwitch">';
		var currentval = $(this).val();
		var defaultvalassigned = false;
		var highlightedval = '';
		
		//add each option to the buffer
		$(this).find('option').each(function(){

			//is this the selected option? If so give it selected class
			if(defaultvalassigned == false && currentval == $(this).val())
			{
				defaultvalassigned = true;
				highlightedval = ' btn_selected';
			}else
				highlightedval = '';
		
			//building buffer...
			buffer = buffer + '<button class="toggleButton' + highlightedval + '" value="' + $(this).val() + '">' + $(this).html() + '</button>';
		});
		
		//close buffer and append
		buffer = buffer + '</span>';
		$(this).wrap('<span>').after(buffer);
		
	});
	
	//toggle status upon a button being clicked
	$(selector).parent().find('.toggleSwitch .toggleButton').click(function(e){

		//prevent default
		e.preventDefault();
		
		//remove selected status from other buttons
		$(this).parent().find('.toggleButton').removeClass('btn_selected');
		
		//add selected status to this button
		$(this).addClass('btn_selected');
		
		//change input value to match that of this buttons value and trigger change event
		$(this).parent().parent().find('select').val($(this).val())
												.change();
	
	});
}

/* DIV based alert overridden
--------------------------------------------- */

var alert_interval = 0;
function alert(x)
{
	if($('#alert_container').length == 0)
		$('body').append('<div id="alert_container"></div>');

	alert_interval = alert_interval + 1;
	$('#alert_container').append('<div id="' + alert_interval + '_alert" class="alertbox">' + x + '</div>');
	setTimeout('$("#' + alert_interval + '_alert").fadeOut();',10000);
}

/* REMOVE www. from the url if its there
---------------------------------------------- */

var url = window.location.toString();
if(url.search('www.') != -1)
window.location = url.replace('www.','');

/* Encode a string for URL
---------------------------------------------- */

function urlencode (str) {
	str = escape(str);
	return str.replace(/[*+\/@]|%20/g,
		function (s) {
			switch (s) {
				case "=": s = "%3D"; break;
				case "*": s = "%2A"; break;
				case "+": s = "%2B"; break;
				case "/": s = "%2F"; break;
				case "@": s = "%40"; break;
				case "%20": s = "+"; break;
				case "?": s = "%3F"; break;
			}
		return s;
		}
	);
}

/* includes cache/page_helper_files/pagename/stylesheet.css and javascript.js automatically ONE time when they load a page
---------------------------------------------- */

var js_pages = new Array();
function includePageJS(pagename) {
	if (!js_pages[pagename]) { 
		$('head').append('<script type=\'text/javascript\' src=\'cache/page_helper_files/' + pagename + '/javascript.js.php?pagename=' + urlencode(pagename) + '\'></script>');
		js_pages[pagename] = true;
	}
}

var css_pages = new Array();
var css_count = 0;
function includePageCSS(pagename) {
	if (!css_pages[pagename]) { 
	
	    var head  = document.getElementsByTagName('head')[0];
	    var link  = document.createElement('link');
	    link.id   = css_count;
	    link.rel  = 'stylesheet';
	    link.type = 'text/css';
	    link.href = 'cache/page_helper_files/' + pagename + '/stylesheet.css';
	    link.media = 'all';
	    head.appendChild(link);
	
		css_pages[pagename] = true;
	}
}

/* Convert url like #!/page/var1/val1/var2/val2 to page.php?var1=val1&var2=val2
---------------------------------------------- */

var newURL;
var urlArray;
function makeURL(newURL)
{
	newURL = newURL.replace("#!","").replace("#","");
	urlArray = newURL.split('/');
	var insert = ".php?";
	newURL = '';
	for(i in urlArray)
	{
		if(urlArray[i] != '')
		{
			newURL = newURL + urlencode(urlArray[i]) + insert;
			if(insert == '.php?' || insert == '&')
				insert = '='
			else
				insert = '&';
		}
	}
	return newURL;
}

/* Checks and navigates to hashtag based URL 2
---------------------------------------------- */

var oldhash = '';
var lastpage = new Array();
var lastpage_array_number = 0;
var newhash = '';
var countnumber = 0;
var pageincludepath = 'pages/';
var GLOBAL_Homepage = 'Home';
var insert_into = '.content';
var insert_into_width;
var pagename = new Array();
var uploadready = false;

function checkhash()
{
	if(window.location.hash == '')
		newhash = '#/' + GLOBAL_Homepage;
	else
		newhash = window.location.hash;

	//if the hash changed change pages, if its blank load the homepage
	if(oldhash != newhash)
	{
		uploadready = false;
		//determine width of content container
		var insert_into_width = $(insert_into).width();
	
		//create new container to insert content into
		countnumber = countnumber + 1;
		$(insert_into).append('<div style="position: absolute; width: ' + insert_into_width + 'px" id="' + countnumber + '_container"></div>')
					  .parent().css('position','relative');
					  
		//declare pointers to new content and old content boxes
		var new_content = $('#' + countnumber + '_container');
		var old_content = $('#' + (countnumber - 1) + '_container');
					  
		//stick loading icon in new content block
		var loadingblock = $('<div class="contentblock_container" style="display: none;"><div class="contentblock loading"><img src="includes/images/large-ajax-loader.gif"></div></div>');
		old_content.prepend(loadingblock);
		$(loadingblock).slideDown();
			
		//update page history array
		lastpage_array_number++;
		lastpage[lastpage_array_number] = newhash;
		
		//since were visiting a new page update the old hash url to page we are now loading
		oldhash = newhash;
		newURL = makeURL(newhash);

		//load the function indicating that the user has left the previous page they were viewing
		eval('if(typeof window.' + pagename[0] + '_onleave == "function") ' + pagename[0] + '_onleave()');
		
		//load in the CSS stylesheet for this page
		pagename = newURL.split('.php');
		includePageCSS(pagename[0]);
		includePageJS(pagename[0]);

		//Insert new content!
		new_content.load(pageincludepath + newURL,function(){
		
		    //run pagename_onload() every time they open this page
		    eval('if(typeof window.' + pagename[0] + '_onload == "function") ' + pagename[0] + '_onload()');
		    
			//fly new container in old out etc
			old_content.css('position','absolute');
			$(insert_into).css('min-height',old_content.height());
			if(lastpage[lastpage_array_number - 2] == newhash)
			{
				//if were navigating back swype from left and clear back interval
				new_content.css('left',$(window).width() * -1).animate({'left':'0px'},400,function(){ $(this).css({'position':'static', 'width':'auto'}) });
				old_content.css('width',insert_into_width).animate({'left':$(window).width() + 'px'},400,function(){ $(this).remove() });
				lastpage_array_number = lastpage_array_number - 2;
			}else{
				//else navigate forward
				new_content.css('left',$(window).width()).animate({'left':'0px'},400,function(){ $(this).css({'position':'static', 'width':'auto'}) });
				old_content.css('width',insert_into_width).animate({'left':($(window).width() * -1) + 'px'},400,function(){ $(this).remove() });
			}
		
		});
	}
}
$(document).ready(function(){
	//insert initial container for content & set parent to static
	$(insert_into).html('<div id="' + countnumber + '_container"></div>');

	//run hash checker all the time
	setTimeout(function(){ setInterval(checkhash, 100) },300);
});

/* JSON function with headers preset
---------------------------------------------- */

function JSON(jsonurl, jsonmethod, jsondata, callback)
{
	$.ajax({ 
		url: jsonurl,
		type: jsonmethod,
		data: jsondata,
		cache: false,
		dataType: 'json',
		success: function(data, status, xhr){ callback(data,status); }
	});
}

/* Runs function when user done typing
--------------------------------------------- */

//keeps track of the node
var FUNCTIONREADY_INCRIMENT = 0;
var FUNCTIONREADY_ARRAY = new Array();
function doneTyping(selector,code,delay)
{
	//find delay
	if(typeof(delay) == 'undefined')
		delay = 800;
	
	//when they keypress down delay the action
	FUNCTIONREADY_INCRIMENT++;
	$(selector).keydown(function(){
		 clearTimeout(FUNCTIONREADY_ARRAY[FUNCTIONREADY_INCRIMENT]);
	});
	
	//set scope
	var scope = $(selector);
	
	//on key up cause pending action
	$(selector).keydown(function(){
		 FUNCTIONREADY_ARRAY[FUNCTIONREADY_INCRIMENT] = setTimeout(function(){ code.call(scope); },delay);
	});
}

/* expands textarea (selector) as you type in it
--------------------------------------------- */

//corrects textarea size
var AUTOHEIGHTINTERVAL = new Array();
var AUTOHEIGHTINCRIMENT = 0;
function autoHeight(selector)
{
	$(selector).each(function(){
		var textarea = this;
		//assign textarea with defaultheight attribute and remove scrollbar
		$(textarea).attr('defaultheight',$(textarea).height())
				   .attr('defaultwidth',$(textarea).width())
				   .css('overflow-y','hidden');
	
		//insert hidden div to calculate size of textarea
		var secretdiv = $('<div style="word-wrap: break-word; position: absolute; left: -9999px;"></div>').css({ 'font-size': $(textarea).css('font-size'), 'font-family': $(textarea).css('font-family'), 'width': $(textarea).width() }).appendTo('body');
	
		//match contents up of textarea and div up and resize where need be
		var setheight = function(){
			$(secretdiv).html($(textarea).val().replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n$/, '<br/>&nbsp;').replace(/\n/g,'<br />'));
			
			if($(secretdiv).height() > $(textarea).attr('defaultheight'))
				$(textarea).css('height',$(secretdiv).height());
			else
				$(textarea).css('height',$(textarea).attr('defaultheight'));
		}
		$(textarea).keyup(setheight).keydown(setheight).change(setheight);
		setheight();
		
		//on resize change div width
		var instanceid = ++AUTOHEIGHTINCRIMENT;
		AUTOHEIGHTINTERVAL[instanceid] = setInterval(function(){
			if($(textarea).width() != $(textarea).attr('defaultwidth'))
			{
				$(textarea).attr('defaultwidth',$(textarea).width());
				$(secretdiv).css('width',$(textarea).width());
				setheight();
				
				//if we moved pages delete interval and div
				if($(textarea).width() == 0)
				{
					$(secretdiv).remove();
					clearInterval(AUTOHEIGHTINTERVAL[instanceid]);
				}
			}
		},300);
	});
}

// Open Window, popup function, learn to use properly

var wposx = 0;
var wposy = 0;
function openWindow(x, y, winWidth, winHeight, speed, button, name, callback) {
	var dialog = false;
	button.attr('disabled', true);
	$('body').prepend('<div id=\'backdrop\'><div id=\'' + name + '\' class=\'window\'></div></div>')
	var scope = $('#' + name).css({opacity: 0.0, width: 0, height: 0, left: x + 'px', top: y + 'px'}).animate({opacity: 1.0, top: (($(window).height() - winHeight) / 2) + 'px', left: (($(window).width() - winWidth) / 2) + 'px', width: winWidth + 'px', height: winHeight + 'px' }, speed);
	dialog = true;
	
	wposx = x;
	wposy = y;
	
	$('#' + name).live('click', function(e) {
			e.stopPropagation();
	});
		
	$('#backdrop').live('click', function() {
		if (dialog) {
			button.attr('disabled', false);
			$('#' + name).animate({opacity: 0.0, width: 0, height: 0, left: x + 'px', top: y + 'px' }, speed);
			setTimeout(function() {$('#backdrop').remove(); }, speed * 2);
			$('button').css('color', '#000').removeAttr('disabled');
			dialog = false;
		}
	});
		
	setTimeout(function() {callback.call(scope);}, speed);
}

/* Complex alert
	var alerttitle	  =   'Thanks for wanting to sell!';
	var alerttext	  =   'Thanks for wanting to put an item up for sale at Habbox Market. Before you do, though, you will need to register an account with us!';
	var alertbuttons  =   '<button style="float: left;" message="register">Register and Continue</button> <button style="float: right;" message="close">Close</button><div style="clear:both;"></div>';
	complexAlert(alerttitle,alerttext,alertbuttons,function(message){
		if(message == 'register')
			window.location = '#/Register';
		$(this).remove();
	});
--------------------------------------------- */

function complexAlert(title,message,buttons,callback)
{
	//build the alert
	var complexAlert = $("<table class='complexAlert' style='width: 100%; height: 100%; position: fixed; top: 0; left: 0;'> \
							<tr valign='middle'> \
								<td style='text-align: center;'> \
									<div class='container'> \
										<div class='alert'> \
											<div class='alertTitle'>" + title + "</div> \
											<div class='alertText'>" + message + "</div> \
											<div class='alertOptions'>" + buttons + "</div> \
										</div> \
									</div> \
								</td> \
							</tr> \
						</table>").appendTo('body');
		
	//run callback through with the message attribute they pressed
	$(complexAlert).find('*[message]').click(function(){
		callback.apply(complexAlert,[$(this).attr('message')]);
	});
	
	return complexAlert;
}

function printIt(printThis) {
  var win = window.open();
  self.focus();
  win.document.open();
  win.document.write('<'+'html'+'><'+'body'+'>');
  win.document.write(printThis);
  win.document.write('<'+'/body'+'><'+'/html'+'>');
  win.document.close();
  win.print();
  win.close();
}

/* FUNCTION TO MAKE A SLIDESHOW
 <div id='slideshow'> <div style='background-image: url(s-ender.jpg)'></div> <div style='background-image: url(in-powers-01.jpg)'></div> </div>
--------------------------------------------- */

var IS_WINDOW_ACTIVE = true;
var HAS_WINDOW_ACTIVE_RUN = false;
function slideshow(parent, width, height,timeseconds)
{
	//global selector to master parent
	var selector = $(parent);
	
	//add timestamp to selector to identify interval
	var TIMESTAMP = new Date().getTime();
	selector.attr('timestarted',TIMESTAMP);
	
	//pointer to each slide
	var allslides = selector.children('div');
	
	//assign each div an id
	var NUMBEROFSLIDES = 0;
	allslides.each(function(){
		NUMBEROFSLIDES++;
		$(this).attr('slide',NUMBEROFSLIDES);
	});
	
	//set dimensions of slideshow
	selector.css({'overflow-x':'hidden','position':'relative'}).add(allslides.css('float','left')).css({'width':width, 'height':height});
	
	//wrap slides within div
	selector.wrapInner('<div class="slides" style="width: ' + (NUMBEROFSLIDES*width) + 'px; height: ' + height + 'px; position: absolute">');
	
	//add page selector
	var page_buffer = '';
	for(i = 1; i <= NUMBEROFSLIDES; i++)
		page_buffer = page_buffer + '<div id="' + i + '" class="icon_slideshow_blank" onclick="slideshow_movetoslide(\'[timestarted=' + TIMESTAMP + ']\',' + i + ')"></div>';
	selector.append('<div class="pageselect">' + page_buffer + '</div>');
	
	//highlight first page
	selector.find('.pageselect #1').first().removeClass('icon_slideshow_blank').addClass('icon_slideshow_selected');
	
	//add current slide to slideshow and number of slides
	selector.attr('currentslide','1')
			.attr('numberofslides',NUMBEROFSLIDES);
		
	//run function to rotate banner every x seconds	
	var loopFunction = function(){
		if(!ISMOUSEOVER && IS_WINDOW_ACTIVE)
		{
			var currentslide = parseInt(selector.attr('currentslide'));
			slideshow_movetoslide(parent, (currentslide == NUMBEROFSLIDES) ? 1 : ++currentslide );
		}
		if($(parent).attr('timestarted') == TIMESTAMP)
			setTimeout(loopFunction,timeseconds*1000);
	};
	setTimeout(loopFunction,timeseconds*1000);
	
	//determine when mouse is not over banner and dont rotate when it is over
	var ISMOUSEOVER = false;
	selector.hover(function(){ ISMOUSEOVER = true },function(){ ISMOUSEOVER = false });
	
	//only flip through tabs when window is active
	if(!HAS_WINDOW_ACTIVE_RUN)
	{
		$(window).focus(function() { IS_WINDOW_ACTIVE = true });
		$(window).blur(function() { IS_WINDOW_ACTIVE = false });
	}
}

function slideshow_movetoslide(parent, slidenumber)
{
	//parent selector
	var selector = $(parent);
	
	//set slide variable
	selector.attr('currentslide',slidenumber);
	
	//slide to slide
	selector.children('.slides').animate('.slides').animate({'left':((slidenumber - 1)*selector.width()*-1)},500,function(){
	
		//highlight right little selector bubble thing
		selector.find('.pageselect div').addClass('icon_slideshow_blank').removeClass('icon_slideshow_selected');
		selector.find('.pageselect #' + slidenumber).removeClass('icon_slideshow_blank').addClass('icon_slideshow_selected');
	
	});
}
