
// The $ is shortcut for the jquery library.
// It can create DOM stuff:
//     $('<div></div>').appendTo('body');
// It can get stuff on the page like getElementById but more powerful:
//     var divs = $('.some-class-here');
//     var oneDiv = $('#some-id');
//     var likeCss = $('div ul.highlight, div li.active');
// It can 'wrap' an html element in a jQuery wrapper, giving it more functions
//     <a id="link1" href="page.html">link</a>
//     var normalElement = document.getElementById('link1');
//     var jqueryElement = $(normalElement);
//     jqueryElement.click(
//         function() {
//             alert("Clicked the link!");
//             return false;
//         }
//     );
//     jQueryElement[0] == normalElement;
//     
// If given a function, it's a shortcut for 'when the DOM is ready' so JS doesn't fire before the page is done loading
//     $(
//         function() {
//              // do some stuff here, safe because the browser DOM is ready.
//              // the page may not be done loading, but that doesn't matter
//              // so this is like a pseudo: browser.dom.onload = function()
//              // instead of the traditional window.onload = function()
//              // the former (fake) example happens before page is done loading, but after DOM is ready.
//              // the latter waits till page is done loading (including all images, etc).
//         }
//     );
// Lots of stuff in it, complicated, but helpful as a util library
// http://docs.jquery.com/

var Popup = {
	init: function() {
	},
	
	// Converts the link to load a popup instead
	convertLink: function(elem) {
		elem = $(elem);
		elem.click(function() {
			Popup.show(elem[0].href);
			return false;
		});
	},
	
	convertAllLinks: function() {
		//console.log('convertAllLinks()');
		var links = $('a.popup');
		for (var i=0; i<links.length; i++) {
			this.convertLink(links[i]);
		};
	},
	
	convertForm: function(form) {
		form = $(form);
		form.submit(function() {
			$.post(
				form[0].action,
				form.serialize(),
				function(data, textStatus) { Popup.onFormLoad(data, textStatus); }
			);
			return false;
		});
	},
	
	onFormLoad: function(data, textStatus) {
		if (data.substr(0, 'redirect '.length) == 'redirect ') {
			// Found 'redirect URL'
			window.location = data.substr('redirect '.length, data.length - 'redirect '.length);
		} else {
			// Load results into the popup
			this.div.html(data);
			this.convertPopupForms();
		}
	},
	
	convertAllForms: function() {
		var forms = $('form.popup');
		for (var i=0; i<forms.length; i++) {
			this.convertForm(forms[i]);
		};
	},
	
	show: function(url) {
		this.div = $('<div class="popup-container"></div>').appendTo('body');
		this.div.load(url, function() { Popup.onLoadPopup(); } );
	},
	
	hide: function() {
		if (this.div) {
			this.div.remove();
			this.div = null;
		}
	},
	
	onLoadPopup: function() {
		this.convertPopupForms();
	},
	
	convertPopupForms: function() {
		var forms = this.div.find('form.popup');
		for (var i=0; i<forms.length; i++) {
			this.convertForm(forms[i]);
		};
	}
	
};

function addLoadEvent(func) { 
	var oldonload = window.onload; 
	if (typeof window.onload != 'function') { 
		window.onload = func; 
	} else { 
		window.onload = function() { 
			if (oldonload) { 
				oldonload(); 
			} 
			func(); 
		} 
	} 
} 

/*
function refreshRunningCommand() {
	window.location = '/running_command'
}
*/

// thank you http://www.somacon.com/p117.php
function setAllCheckboxes(formName, fieldName, checkValue)
{
	if(!document.forms[formName])
		return;
	var objCheckBoxes = document.forms[formName].elements[fieldName];
	if(!objCheckBoxes)
		return;
	var countCheckBoxes = objCheckBoxes.length;
	if(!countCheckBoxes)
		objCheckBoxes.checked = checkValue;
	else
		// set the check value for all check boxes
		for(var i = 0; i < countCheckBoxes; i++)
			objCheckBoxes[i].checked = checkValue;
}

function getElementLeft(elm) 
{
    var x = 0;

    //set x to elmÕs offsetLeft
    x = elm.offsetLeft;

    //set elm to its offsetParent
    elm = elm.offsetParent;

    //use while loop to check if elm is null
    // if not then add current elmÕs offsetLeft to x
    //offsetTop to y and set elm to its offsetParent

    while(elm != null)
    {
        x = parseInt(x) + parseInt(elm.offsetLeft);
        elm = elm.offsetParent;
    }
    return x;
}

function getElementTop(elm) 
{
    var y = 0;

    //set x to elmÕs offsetLeft
    y = elm.offsetTop;

    //set elm to its offsetParent
    elm = elm.offsetParent;

    //use while loop to check if elm is null
    // if not then add current elmÕs offsetLeft to x
    //offsetTop to y and set elm to its offsetParent

    while(elm != null)
    {
        y = parseInt(y) + parseInt(elm.offsetTop);
        elm = elm.offsetParent;
    }

    return y;
}

function showLargeImage(obj)
{
    var imgbox=document.getElementById("imgbox");
    imgbox.style.visibility='visible';
    var img = document.createElement("img");
    img.src=obj.src.replace("thumb-","");
    img.style.width='830px';
    img.style.height='430px';
    if(img.addEventListener){
        img.addEventListener('mouseout',hideLargeImageOnMouseOut,false);
        img.addEventListener('click',hideLargeImageOnMouseOut,false);
    } else {
        img.attachEvent('onmouseout',hideLargeImageOnMouseOut);
        img.attachEvent('onclick',hideLargeImageOnMouseOut);
    }             
    imgbox.innerHTML='';
    imgbox.appendChild(img);
    imgbox.style.left='235px';
    //imgbox.style.left=(getElementLeft(obj)-300) +'px';
    imgbox.style.top=(getElementTop(obj)) + 'px';
}

function hideLargeImageOnMouseOut()
{
    document.getElementById("imgbox").style.visibility='hidden';
}

// Output messages to the javascript console, if available (firebug, safari)
function log(str) {
	if (window.console) {
		console.log(str);
	}
}

// Reformat a value for debugging display.
function debugValue(val) {
    if (typeof val == 'string') {
        val = val.replace(/\\/g, '\\\\');
        val = val.replace(/"/g, '\\"');
        val = val.replace(/\n/g, '\\n');
        val = val.replace(/\r/g, '\\r');
        val = val.replace(/\t/g, '\\t');
        return '"' + val + '"';
    } else {
        return '<Unknown type ' + typeof val + ': ' + val + '>';
    }
}

// TODO: Merge this with debugValue() above.
function debugFormat(value) {
	var s;
	if (typeof value == 'string') {
		value = value.replace(/\\/g, '\\\\');
		value = value.replace(/"/g, '\\"');
		value = value.replace(/\n/g, '\\n');
		value = value.replace(/\t/g, '\\t');
		value = value.replace(/\r/g, '\\r');
		return '"' + value + '"'
	} else if (typeof value == 'object' && value instanceof Array) {
		s = '[';
		for (var i in value) {
			if (i > 0)
				s += ', ';
			s += value[i];
		}
		s += ']';
		return s;
	} else {
		return 'Unknown ' + typeof value + ': ' + value;
	}
}

function replaceWhitespaceHtml(val) {
	// Replace formatting with equivalent HTML whitespace chars.
	val = val.replace(/\n/g, '<br/>\n');
	val = val.replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;');
	return val;
}

////////////////////////////////////////////////////////////////////////////////

function SessionStar(elem) {
	var sessionStar = this;
	this.elem = $(elem);
	this.session_id = $(elem).metadata().session_id;
	this.script_id = $(elem).metadata().script_id;
	this.elem.click(function(e) {
		return sessionStar.click(e);
	});
	this.update();
}

SessionStar.prototype.update = function() {
	var results = null;
	
	if (this.session_id) {
		var url = '/session/get_starred';
		var data = {
			session_id: this.session_id
		}
	} else if (this.script_id) {
		var url = '/script/get_starred';
		var data = {
			script_id: this.script_id
		}
	} else {
		alert('ERROR: SessionStar.update(), both session_id and script_id are not set.');
	}
	
	$.ajax({
		async: false,
		url: url,
		data: data,
		type: 'post',
		dataType: 'json',
		success: function(data) {
			results = data;
		}
	});
	
	if (results.result != 'success') {
		alert('failed!');
	} else {
		this.starred = results.starred;
		if (results.starred) {
			this.elem.attr('src', '/media/images/starred-20.png');
			if (this.session_id) {
				this.elem.attr('title', 'Unstar Session');
			} else {
				this.elem.attr('title', 'Unstar Script');
			}
		} else {
			this.elem.attr('src', '/media/images/unstarred-20.png');
			if (this.session_id) {
				this.elem.attr('title', 'Star Session');
			} else {
				this.elem.attr('title', 'Star Script');
			}
		}
	}
}

SessionStar.prototype.click = function(e) {
	this.starred = !this.starred;
	
	if (this.session_id) {
		var url = '/session/set_starred';
		var data = {
			session_id: this.session_id,
			starred: this.starred
		}
	} else if (this.script_id) {
		var url = '/script/set_starred';
		var data = {
			script_id: this.script_id,
			starred: this.starred
		}
	} else {
		alert('ERROR: SessionStar.update(), both session_id and script_id are not set.');
	}
	
	$.ajax({
		async: false,
		url: url,
		data: data,
		type: 'post',
		dataType: 'json',
		success: function(data) {
			results = data;
		}
	});
	
	e.preventDefault();
	e.stopPropagation();
	
	this.update();
	return false;
}

////////////////////////////////////////////////////////////////////////////////

function selectAll(selectors) {
	$(selectors).attr('checked', true);
}

function selectNone(selectors) {
	$(selectors).attr('checked', false);
}

// Submits a form to the given URL.
function submitForm(form, action) {
	$(form).attr('action', action);
	$(form).submit();
}

function logVisit() {
	// Log this user's visit.
	$.ajax({
		url: '/ajax/log_visit',
		type: 'GET'
	})
	// Repeat every 5 minutes.
	setTimeout(logVisit, 300000);
}

function isBrowserChrome() {
	return /chrome/.test(navigator.userAgent.toLowerCase());
}

function getChromeVersion() {
	var matches = navigator.userAgent.toLowerCase().match(/chrome\/([\d.]+)/);
	if (matches == null) {
		return null;
	} else {
		return matches[1];
	}
}

function isChrome5Beta() {
	var version = getChromeVersion();
	if (version != null && version[0] == '5') {
		return true;
	} else {
		return false;
	}
}

String.prototype.startswith = function(str) {
	return (this.substr(0, str.length) == str);
}

String.prototype.endswith = function(str) {
	return (this.substr(this.length-str.length, str.length) == str);
}

////////////////////////////////////////////////////////////////////////////////

function Popout(elem) {
	var popout = this;
	this.elem = $(elem);
	this.elem.click(function() {
		return popout.onClick();
	});
}

Popout.prototype.onClick = function(e) {
	// Open the URL in a new window (force non-tab).
	window.open(this.elem.metadata().url, '_blank', "height=600, width=800");
	
	// Optionally redirect the opening window to a different URL.
	if (this.elem.metadata().opener_url) {
		window.location = this.elem.metadata().opener_url;
	}
	
	return false;
}

////////////////////////////////////////////////////////////////////////////////

function ButtonSelect(elem) {
	var buttonSelect = this;
	
	this.selectElem = $(elem);
	
	this.elem = $('<div class="button-select-elem"></div>');
	this.selectElem.after(this.elem);
	this.selectElem.hide();
	
	this.buttons = [];
	
	for (var i=0; i<this.selectElem.attr('options').length; i++) {
		var button = $('<a href="#" />').appendTo(this.elem);
		
		button.html(
			$(this.selectElem.attr('options')[i]).text()
		);
		
		button.data('value', $(this.selectElem.attr('options')[i]).val());
		
		//log("this.selectElem.attr('options')[i].disabled:");
		//log(this.selectElem.attr('options')[i].disabled);
		
		if (this.selectElem.attr('options')[i].disabled) {
			// This option is disabled.
			button.click(function(e) {
				return false;
			});
			button.addClass('disabled');
		} else {
			// Option is enabled.
			button.click(function(e) {
				//log('clicked on button');
				//log($(this).data('value'));
				buttonSelect.onChange($(this).data('value'));
				return false;
			});
		}
		
		this.buttons.push(button);
	}
	
	$('<br style="clear:both;" />').appendTo(this.elem);
	
	this.selectElem.change(function() {
		buttonSelect.onChange($(this).val());
	});
	
	buttonSelect.onChange(this.selectElem.val());
}

ButtonSelect.prototype.onChange = function(value) {
	//log('ButtonSelect.onChange()');
	//log('  value: ' + value);
	
	for (var i=0; i<this.buttons.length; i++) {
		if (value == this.buttons[i].data('value')) {
			//log('  found button ' + i);
			this.elem.find('a').removeClass('selected');
			this.buttons[i].addClass('selected');
			if (this.selectElem.val() != value) {
				//log('  selectElem is out of date');
				for (var j=0; j<this.selectElem.attr('options').length; j++) {
					if (this.selectElem.attr('options')[j].value == value) {
						//log('  found option ' + j);
						this.selectElem.attr('selectedIndex', j);
						//this.selectElem.attr('options')[j].click();
					}
				}
			}
		}
	}
}

////////////////////////////////////////////////////////////////////////////////

// Run on startup //

$(function() {
	Popup.convertAllLinks();
	Popup.convertAllForms();
	
	$.jGrowl.defaults.position = 'center';
	
	$('.session-star, .script-star').each(function() {
		new SessionStar(this);
	});
	
	$('.rename-script').each(function() {
		new RenameScript(this);
	});
	
	$('a.confirm').click(function(e) {
		return confirm('Are you sure?');
	});
	
	$('.popout').each(function() {
		new Popout(this);
	});
	
	$('.button-select').each(function() {
		new ButtonSelect(this);
	});
	
	// Log this user's visit after 5 seconds.
	setTimeout(logVisit, 5000);
});
