/* ========================  ======================== */
/* ------------------------  ------------------------ */
/* ........................  ........................ */

// ------------------------ Fix IE background image flicker ------------------------ 

/*@cc_on 
	/*@if (@_win32)
		document.execCommand("BackgroundImageCache",false,true); 
	/*@end	
@*/


// ------------------------ Get the scrolled distance (in an array) ------------------------ 

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}


/* ======================== convert link to open new window ======================== */

function openInNewWindow(query, vars) {
	var thisCommand = new Array();
	thisCommand[1] = 'newWindow';
	thisCommand[2] = vars;
	if (!vars) {
		thisCommand[2] = 'toolbar=0,menubar=0,width=747,height=609';
	}
	$(query).each(function(){
		thisCommand[0] = this.href;
		$(this).click(function(){
			window.open(thisCommand[0],thisCommand[1],thisCommand[2]);
			return false;
		});
	});
}

/* ======================== font resize detection ======================== */

function chk_fontResize() {
	if (chk_fontResize.obj.offsetHeight != chk_fontResize.last) {
		chk_fontResize.last = chk_fontResize.obj.offsetHeight;
		// ADD FUNCTION CALLS TO TRIGGER BELOW
		expandMenu('menu1');
		setPageHeight();
	}
}
chk_fontResize.last = 0;



/* ======================== page main element height adjustment ======================== */

function setPageHeight () {
	var windowHeight = $(window).height();
	var bodyHeight 	 = $('#page_inner').height();
	
	if (bodyHeight < windowHeight)
	{
		$('#page').css("height", windowHeight+"px");
	} else
	{
		$('#page').css("height", "auto");
	}
}

/* ======================== semi-fixed scrollable positioning ======================== */

function posSemiFixed(me) {
	// document.all &&(parseInt($.browser.version) < 7)
	if (me.offsetWidth > $(window).width()) {
		var left = getScrollXY()[0];
	} else {
		var left = ($(window).width() / 2 ) - (me.offsetWidth / 2) + getScrollXY()[0];
	}
	
	if (me.offsetHeight > $(window).height()) {
		var top = getScrollXY()[1];
	} else {
		var top = ($(window).height() / 2 ) - (me.offsetHeight / 2) + getScrollXY()[1];
	}
	
	me.style.left = left + 'px';
	me.style.top = top + 'px';
}

/* ======================== slap IE6 ======================== */

function slapIE6(me) {
	me.css('height','1%');
	me.css('height','auto');
}

/* ======================== menu handling ======================== */
/* ------------------------ expand menu items ------------------------ */
function expandMenu (that) {
	var new_height = 0;
	
	//Itterates all menu items and stores the heighest height-value.
	var menuElements = $('#'+that+' .i4th').each( function () {
		this.style.height = 'auto';
		if (this.offsetHeight > new_height) {
			new_height = this.offsetHeight;
		}
	});
	
	//Itteratets all menu items and sets new value for height;
	menuElements.each( function () {
		this.style.height = new_height+"px";
	});
}


/* ------------------------ create table menu for IE ------------------------ */

function init_IEMenu(that){
	var tempID = 'sysex_'+that;
	$('#'+that).after('<table id="'+tempID+'"><tr></tr></table>');
	$('#'+that+' a').each(function(i){
		$('#'+tempID+' tr').append('<td></td>');
		var putItHere = $('#'+tempID+' td')[i];
		$(this).clone().appendTo(putItHere);
	});

	$('#'+that).remove();
	$('#'+tempID).attr('id',that);
	
	$('#'+that+' td:first-child').addClass('first');
	$('#'+that+' td:last-child').addClass('last');
}

/* ------------------------ scrollBottom ------- */
function scrollBottom()
{
	window.scrollBy(0,1900);
	//$(window).scrollTop(10).scrollTop(100);
}


/* ------------------------ handle default values for inputs and textareas ------------------------ */

function init_inputDefVal(){
	$('input[class*=inputDefVal], textarea[class*=inputDefVal]').each(function(i){
		var inputVar = extrClassNameVar(this.className, 'inputDefVal');
		if (($(this).val() == '') || ($(this).val() == inputVar)) {
			$(this).val(inputVar);
			$(this).addClass('inactive');
		}
	});
	
	$('input[class*=inputDefVal], textarea[class*=inputDefVal]').click(function(i){
		var inputVar = extrClassNameVar(this.className, 'inputDefVal');
		if (($(this).val() == '') || ($(this).val() == inputVar)) {
			$(this).removeClass('inactive');
			$(this).val('');
		}
	});
	
	$('input[class*=inputDefVal], textarea[class*=inputDefVal]').focus(function(i){
		var inputVar = extrClassNameVar(this.className, 'inputDefVal');
		if (($(this).val() == '') || ($(this).val() == inputVar)) {
			$(this).removeClass('inactive');
			$(this).val('');
		}
	});
	
	$('input[class*=inputDefVal], textarea[class*=inputDefVal]').blur(function(i){
		if ($(this).val() == '') {
			var inputVar = extrClassNameVar(this.className, 'inputDefVal');
			$(this).addClass('inactive');
			$(this).val(inputVar);
		}
	});
}

/* ........................ extract parameters from classnames ........................ */

function extrClassNameVar(classNameAttr,identifier){
	var extractedUrl;
	var classNameAttr = classNameAttr.split("''");
	for (i = 0; i < classNameAttr.length; i++) {
		if (classNameAttr[i].indexOf(identifier) >= 0) {
			extractedUrl = classNameAttr[(i+1)];
			return extractedUrl;
			break;
		}
	}
}

/* ======================== upload form ======================== */

var uploadForm = {};

uploadForm.init = function() {
	$('.btn_upload').click(function(){
		uploadForm.show();
		return false;
	});
	
	$('#btn_uploadTerms').click(function(){
		$('#lightBox2').addClass('lb_showTerms');
		return false;
	});
	
	$('#upload_terms .ctrl').click(function(){
		$('#lightBox2').removeClass('lb_showTerms');
		return false;
	});

	$("#upload_field_successMsg .ctrl a").click( function() { // close lightbox
		uploadForm.hide();
		return false;
	});
}

uploadForm.show = function(){
	$('#lightBox2, #lightBoxShade1').removeClass('hide');
	posSemiFixed($('#lightBox2')[0]);
}

uploadForm.hide = function(){
	$('#lightBox1, #lightBox2')
		.attr('style','')
		.addClass('hide')
		.removeClass('lb_showTerms')
		.removeClass('lb_onFail')
		.removeClass('lb_onSuccess');
	$('#lightBoxShade1').addClass('hide');
	if (document.all &&(parseInt($.browser.version) < 7)) { // show selectboxes for IE6
		$('#page_footer select, #search1 select').css({ visibility: 'visible' });
	}
}


uploadForm.onSuccess = function() {
	$('#lightBox2')
		.removeClass('lb_showTerms')
		.removeClass('lb_onFail')
		.addClass('lb_onSuccess');
}

uploadForm.onFail = function() {
	$('#lightBox2')
		.removeClass('lb_showTerms')
		.removeClass('lb_onSuccess')
		.addClass('lb_onFail');
}

/* ======================== heightEqualiser ======================== */

function heightEqual(jQExpr) {
	var normHeight = 0;
	$(jQExpr).css('height','auto');
	
	$(jQExpr).each(function(){
		if ($(this).height() > normHeight) {
			normHeight = $(this).height();
		}
	});
	
	$(jQExpr).each(function(){
		$(this).height(normHeight);
	});
}

/* ======================== btn_biggie ======================== */

var btn_biggie = {};

btn_biggie.init = function(){
	if ($.support.opacity) {
		$('.btn_biggie').hover(function(){
			$('.biggie-moImg',this).stop().fadeTo(150,1);
		},function(){
			$('.biggie-moImg',this).stop().fadeTo(200,0);
		});
	} else {
		$('.btn_biggie').hover(function(){
			$('.biggie-moImg',this).css('top','0px');
		},function(){
			$('.biggie-moImg',this).css('top','-9999px');
		});
	}
	
};


/* ======================== neoInputs ======================== */

var ni = {};

ni.replace = function() {
	$('.ni_replace').each(function(){
		if (this.nodeName == 'SELECT') {
			ni.select.replace(this);
		} else if ($(this).is('[type=button],[type=submit],[type=reset],button')) {
			ni.button.replace(this);
		} else if ($(this).hasClass('ni_selectMulti')) {
			ni.selectMulti.replace(this);
		}
	});
}

ni.init = function() {
	$('body').click(function(e){
		if ($(e.target).parents('.ni_replace').length == 0) {
			$('.neoInput ul').hide();
		}
	});
}

/* ------------------------ ni_button ------------------------ */

ni.button = {};

ni.button.replace = function(elem) {
	$(elem).wrap('<a href="javascript:void(0)" class="ni_button"></a>');
	if (elem.nodeName == 'BUTTON') {
		$(elem).parent().append('<span class="$">'+$(elem).html()+'</span>');
	} else {
		$(elem).parent().append('<span class="$">'+$(elem).val()+'</span>');
	}
	$(elem).hide();
	$(elem).parent().click(function(){
		$(this).children(':not("span")').click();
	});
}

/* ------------------------ ni_select ------------------------ */

ni.select = {};

ni.select.replace =  function(elem) {
	$(elem).wrap('<div class="neoInput ni_select"></div>');
	$(elem).parent().prepend('<a href="#" class="ni_label">'+$(elem).attr('title')+'</a><a href="#" class="ni_ctrl" title="Select"></a><div class="ni_pos"><ul></ul></div>');
	$('option',$(elem)).each(function(){
		$('ul',$(elem).parent()).append('<li><a href="#" rel="'+$(this).val()+'">'+$(this).html()+'</a></li>');
	});

	var chkSel = -1;
	$('option',$(elem)).each(function(i){
		if($(this).attr('selected') == true) {
			chkSel = i; 
		}
	});
	
	if (chkSel >= 0) {
		$('ul li a',$(elem).parent()).eq(chkSel).addClass('ni_selected');
		$('.ni_label',$(elem).parent()).html($('.ni_selected',$(elem).parent()).html());
	}
	
	ni.select.init($(elem).parent()[0]);
}

ni.select.init = function(elem) {
	$('a.ni_label, a.ni_ctrl',elem).click(function(){
		$('.ni_select ul, .ni_selectMulti ul').not($('ul',$(this).parent())).hide(); // close all other selects
		$('ul',$(this).parent()).toggle(); // toggle this select
		return false;
	});
	
	$('ul a',elem).click(function(){
		var scope = $(this).parents('.ni_select').eq(0);
		$('a.ni_selected',scope).removeClass('ni_selected');
		$(this).addClass('ni_selected');
		$('a.ni_label',scope).html($(this).html());
		$(this).parent().parent().hide();
		
		$('select',scope).val($(this).attr('rel'));

		$('select',scope).change();

		return false;
	});
}

/* ------------------------ selectMulti ------------------------ */

ni.selectMulti = {};

ni.selectMulti.replace =  function(elem) {
	$(elem).wrap('<div class="neoInput ni_select ni_selectMulti"></div>');
	$(elem).parent().prepend('<a href="#" class="ni_label">'+$(elem).attr('title')+'</a><a href="#" class="ni_ctrl" title="Select"></a><div class="ni_pos"><ul></ul></div>');
	
	$('[type=checkbox]',$(elem)).each(function(){
		var relVal = ($(this).attr('name') != '') ? $(this).attr('name') : $(this).attr('id');
		var chkmark = ($(this).is(':checked')) ? ' class="checked"' : '';
		$('ul',$(elem).parent()).append('<li><a href="#" rel="'+relVal+'"'+chkmark+'>'+$(this).next('label').html()+'</a></li>');
	});
	$('ul',$(elem).parent()).prepend('<li><a href="#" class="selectAll"><strong>'+ni.selectMulti.selectAllText+'</strong></a></li>')
	
	ni.selectMulti.init($(elem).parent()[0]);
}

ni.selectMulti.init = function(elem) {
	$('a.ni_label, a.ni_ctrl',elem).click(function(){
		$('.ni_select ul, .ni_selectMulti ul').not($('ul',$(this).parent())).hide(); // close all other selects
		$('ul',$(this).parent()).toggle(); // toggle this select
		return false;
	});
	
	if ($('span input',elem).length == $('span input:checked').length) {
		$('ul .selectAll',elem).addClass('checkedAll');
	}
	
	$('ul a',elem).not('.selectAll').click(function(){
		var scope = $(this).parents('.ni_select').eq(0);
		
		if ($(this).hasClass('checked')) {
			$(this).removeClass('checked');
			$('span input',scope).val($(this).attr('rel'));
			$('#'+$(this).attr('rel')+',[name='+$(this).attr('rel')+']').removeAttr('checked');
		} else {
			$(this).addClass('checked');
			$('span input',scope).val($(this).attr('rel'));
			$('#'+$(this).attr('rel')+',[name='+$(this).attr('rel')+']').attr('checked','checked');
		}

		return false;
	});
	
	$('ul a.selectAll',elem).click(function(){
		var scope = $(this).parents('.ni_select').eq(0);
		
		if ($(this).hasClass('checkedAll')) {
			$(this).removeClass('checkedAll');
			//$('span input',scope).val($(this).attr('rel'));
			//$('#'+$(this).attr('rel')+',[name='+$(this).attr('rel')+']').removeAttr('checked');
			$('ul a',scope).removeClass('checked');
			$('span input',scope).removeAttr('checked');
		} else {
			$(this).addClass('checkedAll');
			//$('span input',scope).val($(this).attr('rel'));
			$('ul a',scope).not('.selectAll').addClass('checked');
			$('span input',scope).attr('checked','checked');
		}

		return false;
	});
}

ni.selectMulti.selectAllText = 'Check/uncheck all';


/* ======================== Persistant inputs ======================== */

var persistantInput = {};

persistantInput.init = function() {
	$('.persistantInput').prev('input[type=text],textarea').each(function(){
		$(this).val($(this).next('.persistantInput').text());
		$(this).focus(function(){
			if ($(this).val() == $(this).next('.persistantInput').text()) {
				$(this).val('');
			}
		});
		$(this).blur(function(){
			if ($(this).val() == '') {
				$(this).val($(this).next('.persistantInput').text());
			}
		});
	})
}

/* ======================== ON READY ======================== */

$(document).ready( function () {
	
	/* --------- set mozilla class ---------- */

	if (navigator.product) {
		if ((navigator.product.indexOf('Gecko') > -1) && (navigator.appVersion.indexOf('KHTML') == -1)) {
			$('body').addClass('sys_gecko');
			//alert($('body').attr('class'));
		}
	}
							 
	/* --------- Defines page height ---------- */
	setPageHeight();
	$(window).resize(function(){
		setPageHeight()
	});
	
	/* --------- Check if font-size been altered ---------- */
	setInterval("chk_fontResize()", 500);
	chk_fontResize.obj = $("#ctrl_skipCont")[0];
	
	/* --------- input/textarea default values ---------- */
	init_inputDefVal();
	
	
	/* --------- open links in new windows ---------- */
	openInNewWindow('.aa_settings_link');
	
	
	/* --------- other ---------- */
	
	ni.replace();
	
	ni.init();
	
	heightEqual('#toolbar .content_box');
	
	btn_biggie.init();
	
	uploadForm.init();
	
	persistantInput.init();
	
	/* --------- IE6 specific ---------- */
	//if (document.all && !window.opera) {
	if (document.all && (parseInt($.browser.version) < 8)) {
		init_IEMenu('menu1');
		$(window).resize(function(){
			expandMenu('menu1')
		});
		init_IEMenu('menu1');
		$("#menu1 a").hover(function(){
			$(this).css('display', 'block');
		},function(){
		  	$(this).css('display', 'block');
		});
	}
});