//------------------------------------------------------------------------------
//  http://keytrack.de  -  Keytrack.de  -  Keytrack.de Home  - 
//------------------------------------------------------------------------------
//***** automation.js *****  some javascript automation stuff, requires jquery
//------------------------------------------------------------------------------



// --- affilite network slider
var page = {};
jQuery(function() {
	new FrontPage().init();
});


// --- image preloading
var imgs = ['http://keytrack.de/img/ajax-loader.gif', 'http://keytrack.de/img/ajax-tile-loader.gif'],
	i2s = [];
for (var i=0; i<imgs.length; i++) {
	i2s[i] = new Image();
	i2s[i].src = imgs[i];
}


// --- popupstatus init
var popupStatus = 0;


//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

jQuery(document).ready(function() {

	// --- add rounded corners to boxes
	jQuery('.more-button, .big-button, .more-link, .left-head, .blog-box, .box-rounded, #l_sidebar, #l_sidebar ul li, '+
		'#l_sidebar ul li ul li a, #posts-content').corner('8px');
	jQuery('.box-rounded-5px, .wp-pagenavi a, .wp-pagenavi span, .admin-menu ul li a').corner('5px');

	// --- cufon font replacements
	Cufon.replace('h2',{hover:'true'}) ('h3',{hover:'true'}) ('h4') ('h5') ('h6') ('.slide-more') ('.heading1-slide')
		('.heading2-slide') ('ul.navigation',{hover:'true'}) ('ul#menu-topright li') ('.fix-font') ('.more-button') 
		('.more-link') ('#networks-scroller #text');

	// --- intial value automation of all form input fields
	automateInputs( ['#login-user', '#login-pw', '#search-input'] );

	// --- animate login form
	var	$formdiv = jQuery('div#login-form'),
		$user = jQuery('input#login-user'),
		$pass = jQuery('input#login-pw'),
		$submit = jQuery('div#login-submit'),
		$cancel = jQuery('div#login-cancel');
	jQuery('div#login-toggle').click(function() {
		jQuery(this).fadeOut(200, function(){
			$formdiv.css('display','inline');
			$user.hide();
			$pass.hide();
			$submit.hide();
			$cancel.hide();
			$formdiv.animate({ width:'340px' },400, function() {
				$user.fadeIn(200);
				$pass.fadeIn(200);
				$submit.fadeIn(200);
				$cancel.fadeIn(200);
			});
			jQuery('div#admin-menu').animate({ backgroundColor: '#ccc' },300, function() {
				jQuery(this).animate({ backgroundColor: '#eaeaf0' },500);
			});
		});
	});
	$cancel.click(function () {
		$user.fadeOut(100);
		$pass.fadeOut(100);
		$cancel.fadeOut(100);
		$submit.fadeOut(100, function() {
			$formdiv.animate({ width:'85px' },400, function() {
				$formdiv.css('display','none');
				jQuery('div#login-toggle').fadeIn(300);
			});
		});
		jQuery('div#admin-menu').animate({ backgroundColor: '#ccc' },300, function() {
			jQuery(this).animate({ backgroundColor: '#eaeaf0' },500);
		});
	});
	
	// --- login form ajax events
	var $loginform = jQuery('form#login');
 	$loginform.submit(function(e) {
		ajaxActivateButton('div#login-submit');
		e.preventDefault();
		var	$oc = $submit.find('span.label'),
			ocnt = $oc.html(),
			user = $user.val(),
			pass = $pass.val();
		$oc.html('');
		$oc.addClass('ajax-loader-bg');
		jQuery.ajax({
			type: 'POST',
			timeout: 7000,
			data: {ajax:true, user:user, pass:pass},
			url: 'login.php',
			success: function(data) {
				if (data==='1') {
					$loginform.unbind();
					$loginform.submit();
				} else {
					jQuery('div#error').html(data);
					showStatus('error');
					$oc.removeClass('ajax-loader-bg');
					$oc.html(ocnt);
				}
			},
			error: function() {
				window.location.href = 'login.php';
			}
		});
	});
	$submit.click(function() {
		$loginform.submit();
	});
	$pass.keypress(function(e) {
		if(e.which == 10 || e.which == 13) {
			$loginform.submit();
		} 
	});
	
	// --- animate status / error box messages
	var boxes = [ 'error', 'statusmsg' ], st;
	for (var i=0; i<boxes.length; i++) {
		st = jQuery('div#'+boxes[i]).html().replace(/<(.|\n)*?>/g, '');
		st = jQuery.trim(st);
		if (st!='') {
			showStatus('statusmsg');
		}
	}
	
	// --- download plugin popup and email validation
	jQuery('#button-download-plugin').click(function() {
		loadIntoPopup('#download-plugin-popup',450);
		Cufon.replace('#popup div.download-plugin-popup-content h1');
		automateInputs(['.plugin-email-input']);
		centerPopup();
		showPopup();
		jQuery('#popup div.download-plugin-submit').click(function(){
			pluginDownloadSubmit();
		});
		jQuery('#popup input.plugin-email-input').keypress(function(e) {
			if(e.which == 10 || e.which == 13) {
				pluginDownloadSubmit();
			} 
		});
	});

	// --- generic popup close events
	jQuery('#popup-close').click(function() {
		hidePopup();
	});
	jQuery('#popup-background').click(function() {
		hidePopup();
	});
	jQuery(document).keypress(function(e) {
		if(e.keyCode==27 && popupStatus==1) {
			hidePopup();
		}
	});

});


//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------


function pluginDownloadSubmit() {

	var submit = '#popup div.download-plugin-submit';
	ajaxActivateButton(submit);
	
	var email = jQuery('#popup input.plugin-email-input').val();
	
	jQuery.ajax({
		type: 'POST',
		timeout: 7000,
		data: {ajax:true, email:email},
		url: 'register.php',
		success: function(dataJ) {
			var data = jQuery.parseJSON(dataJ);
			console.log(data);
			if (data.status==='0') {
				ajaxDeactivateButton(submit);
			} else if (data.status==='not_valid') {
				ajaxDeactivateButton(submit);
				$error = jQuery('#popup div.submit-error');
				$error.hide();
				$error.css('visibility','visible');
 				$error.fadeIn(300, function(){
					$error.fadeTo(5000,100, function(){
						$error.fadeOut(2500);
					});
				});
 			} else {
				ajaxDeactivateButton(submit);
				var $innercontent = jQuery('#popup .inner-content');
				$innercontent.fadeOut(400, function(){
					var ncnt = jQuery('div#download-plugin-email-confirmed').html();
					$innercontent.html(ncnt);
					if (data.status==='already_registered') {
						jQuery('#popup .accepted').hide();
						jQuery('#popup .already-registered').removeClass('no-display');
						jQuery('#popup .already-registered').show();
					}
					$innercontent.fadeIn(400, function(){
						jQuery('#popup div.zip-download-container').wrap('<a href="'+data.url+'" title="Download Keytrack.de Wordpress Plugin"></a>');
					});
				});
			}
		},
		error: function() {
			window.location.href = 'register.php';
		}
	});
}

//-----------------------------------------------------------------------------


// --- turn on and off active state of ajax buttons:

function ajaxActivateButton(button)
{
	var $button = jQuery(button);
	$button.addClass('ajax-bg');
	$button.hover(function(){
		$button.addClass('ajax-bg');
	}, function(){
		$button.addClass('ajax-bg');
	});
}

function ajaxDeactivateButton(button)
{
	var $button = jQuery(button);
	$button.removeClass('ajax-bg');
	$button.hover(function(){
		$button.removeClass('ajax-bg');
	}, function(){
		$button.removeClass('ajax-bg');
	});
}

//-----------------------------------------------------------------------------


// --- specify initial hint values in form input fields:

function automateInputs(ids)
{
	var elm, oval;
	
	for (var i=0; i<ids.length; i++) {
		elm = jQuery('input'+ids[i]);
		oval = elm.val();
		elm.focus({ov: oval}, function(e) {
			var ov = e.data.ov;
			if (this.value == ov) { this.value = ''; }
		});
		elm.blur({ov: oval}, function(e) {
			var ov = e.data.ov;
			if (this.value == '') { this.value = ov; }
		});
	}
}

//-----------------------------------------------------------------------------


// --- display or hide error and status messages:

function showStatus(which)
{
	if (which=='error')
		var tclr = '#f6dcdc';
	else
		var tclr = '#dcdcf6';

	var	dv = jQuery('div#'+which),
		bgc = dv.css('background-color');
	dv.css('background-color',tclr);
	
	dv.fadeIn(300, function() {
		jQuery(this).fadeTo(500, 100, function() {
			jQuery(this).animate({ backgroundColor: bgc}, 400, function() {
				jQuery(this).animate({ backgroundColor: tclr}, 300, function() { 
					jQuery(this).fadeTo(1500, 100, function() {
						jQuery(this).fadeOut(3000, function() {
							jQuery(this).css('background-color',bgc);
						});
					});
				});
			});
		});
	});
}

//-----------------------------------------------------------------------------


// --- popup handling:

function loadIntoPopup(content, width, height)
{
	var $ppc = jQuery('#popup-content');
	if (typeof width != 'undefined') {
		$ppc.css({ 
			'width': width+'px' 
		});
	}
	if (typeof height != 'undefined') {
		$ppc.css({ 
			'height': height+'px' 
		});
	}
	$ppc.html(jQuery(content).html());
}

function showPopup()
{
	if(popupStatus==0) {
		var $bg = jQuery('#popup-background');
		$bg.css({
			'opacity': '0.5'
		});
		$bg.fadeIn('slow');
		jQuery('#popup').fadeIn('slow');
		popupStatus = 1;
	}
}

function hidePopup() 
{
	if(popupStatus==1) {
		jQuery('#popup-background').fadeOut('slow');
		jQuery('#popup').fadeOut('slow', function(){
			jQuery('#popup-content').html('');
		});
		popupStatus = 0;
	}
}

function centerPopup() 
{
	var $pp = jQuery('#popup');
	var windowWidth = jQuery(window).width();
	var windowHeight = jQuery(window).height();
	var popupWidth = $pp.width();
	var popupHeight = $pp.height();
	$pp.css({
		'position': 'absolute',
		'top': windowHeight/2-popupHeight/2,
		'left': windowWidth/2-popupWidth/2
	});
	jQuery('#popup-background').css({
		'height': windowHeight
	});
}

//-----------------------------------------------------------------------------


// --- jquery color plugin:

(function(d){d.each(['backgroundColor','borderBottomColor','borderLeftColor','borderRightColor','borderTopColor','color','outlineColor'],function(f,e){d.fx.step[e]=function(g){if(!g.colorInit){g.start=c(g.elem,e);g.end=b(g.end);g.colorInit=true}g.elem.style[e]='rgb('+[Math.max(Math.min(parseInt((g.pos*(g.end[0]-g.start[0]))+g.start[0]),255),0),Math.max(Math.min(parseInt((g.pos*(g.end[1]-g.start[1]))+g.start[1]),255),0),Math.max(Math.min(parseInt((g.pos*(g.end[2]-g.start[2]))+g.start[2]),255),0)].join(',')+')'}});function b(f){var e;if(f&&f.constructor==Array&&f.length==3){return f}if(e=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(f)){return[parseInt(e[1]),parseInt(e[2]),parseInt(e[3])]}if(e=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(f)){return[parseFloat(e[1])*2.55,parseFloat(e[2])*2.55,parseFloat(e[3])*2.55]}if(e=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(f)){return[parseInt(e[1],16),parseInt(e[2],16),parseInt(e[3],16)]}if(e=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(f)){return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)]}if(e=/rgba\(0, 0, 0, 0\)/.exec(f)){return a.transparent}return a[d.trim(f).toLowerCase()]}function c(g,e){var f;do{f=d.curCSS(g,e);if(f!=''&&f!='transparent'||d.nodeName(g,'body')){break}e='backgroundColor'}while(g=g.parentNode);return b(f)}var a={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]}})(jQuery);

//-----------------------------------------------------------------------------


//** Smooth Navigational Menu- By Dynamic Drive DHTML code library: http://www.dynamicdrive.com
//** Script Download/ instructions page: http://www.dynamicdrive.com/dynamicindex1/ddlevelsmenu/
//** Menu created: Nov 12, 2008

var ddsmoothmenu={

//Specify full URL to down and right arrow images (23 is padding-right added to top level LIs with drop downs):
arrowimages: {down:['downarrowclass', '/keytrack.de/img/down2.png', 23], right:['rightarrowclass', '/keytrack.de/img/right-arrow.gif']},
transition: {overtime:300, outtime:300}, //duration of slide in/ out animation, in milliseconds
shadow: {enable:false, offsetx:5, offsety:5}, //enable shadow?
showhidedelay: {showdelay: 100, hidedelay: 200}, //set delay in milliseconds before sub menus appear and disappear, respectively

///////Stop configuring beyond here///////////////////////////

detectwebkit: navigator.userAgent.toLowerCase().indexOf('applewebkit')!=-1, //detect WebKit browsers (Safari, Chrome etc)
detectie6: document.all && !window.XMLHttpRequest,
css3support: window.msPerformance || (!document.all && document.querySelector), //detect browsers that support CSS3 box shadows (ie9+ or FF3.5+, Safari3+, Chrome etc)

getajaxmenu:function($, setting){ //function to fetch external page containing the panel DIVs
	var $menucontainer=jQuery('#'+setting.contentsource[0]) //reference empty div on page that will hold menu
	$menucontainer.html('Loading Menu...')
	jQuery.ajax({
		url: setting.contentsource[1], //path to external menu file
		async: true,
		error:function(ajaxrequest){
			$menucontainer.html('Error fetching content. Server Response: '+ajaxrequest.responseText)
		},
		success:function(content){
			$menucontainer.html(content)
			ddsmoothmenu.buildmenu($, setting)
		}
	})
},


buildmenu:function($, setting){
	var smoothmenu=ddsmoothmenu
	var $mainmenu=jQuery('#'+setting.mainmenuid+'>ul') //reference main menu UL
	$mainmenu.parent().get(0).className=setting.classname || 'ddsmoothmenu'
	var $headers=$mainmenu.find('ul').parent()
	$headers.hover(
		function(e){
			jQuery(this).children('a:eq(0)').addClass('selected')
		},
		function(e){
			jQuery(this).children('a:eq(0)').removeClass('selected')
		}
	)
	$headers.each(function(i){ //loop through each LI header
		var $curobj=jQuery(this).css({zIndex: 100-i}) //reference current LI header
		var $subul=jQuery(this).find('ul:eq(0)').css({display:'block'})
		$subul.data('timers', {})
		this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
		this.istopheader=$curobj.parents('ul').length==1? true : false //is top level header?
		$subul.css({top:this.istopheader && setting.orientation!='v'? this._dimensions.h+'px' : 0})
		$curobj.children('a:eq(0)').css(this.istopheader? {paddingRight: smoothmenu.arrowimages.down[2]} : {}).append( //add arrow images
			'<img src="'+ (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[1] : smoothmenu.arrowimages.right[1])
			+'" class="' + (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[0] : smoothmenu.arrowimages.right[0])
			+ '" style="border:0;" />'
		)
		if (smoothmenu.shadow.enable && !smoothmenu.css3support){ //if shadows enabled and browser doesn't support CSS3 box shadows
			this._shadowoffset={x:(this.istopheader?$subul.offset().left+smoothmenu.shadow.offsetx : this._dimensions.w), y:(this.istopheader? $subul.offset().top+smoothmenu.shadow.offsety : $curobj.position().top)} //store this shadow's offsets
			if (this.istopheader)
				$parentshadow=jQuery(document.body)
			else{
				var $parentLi=$curobj.parents('li:eq(0)')
				$parentshadow=$parentLi.get(0).$shadow
			}
			this.$shadow=jQuery('<div class="ddshadow'+(this.istopheader? ' toplevelshadow' : '')+'"></div>').prependTo($parentshadow).css({left:this._shadowoffset.x+'px', top:this._shadowoffset.y+'px'})  //insert shadow DIV and set it to parent node for the next shadow div
		}
		$curobj.hover(
			function(e){
				var $targetul=$subul //reference UL to reveal
				var header=$curobj.get(0) //reference header LI as DOM object
				clearTimeout($targetul.data('timers').hidetimer)
				$targetul.data('timers').showtimer=setTimeout(function(){
					header._offsets={left:$curobj.offset().left, top:$curobj.offset().top}
					if (header._offsets.left+menuleft+header._dimensions.subulw<=jQuery(window).width()) {
						$targetul.find('a').css('text-align', 'right');
					}
					var menuleft=header.istopheader && setting.orientation!='v'? 0 : header._dimensions.w
					menuleft=(header._offsets.left+menuleft+header._dimensions.subulw>jQuery(window).width())? (header.istopheader && setting.orientation!='v'? -header._dimensions.subulw+header._dimensions.w : -header._dimensions.w) : menuleft //calculate this sub menu's offsets from its parent
					if ($targetul.queue().length<=1){ //if 1 or less queued animations
						$targetul.css({left:menuleft+'px', width:header._dimensions.subulw+'px'}).animate({height:'show',opacity:'show'}, ddsmoothmenu.transition.overtime)
						if (smoothmenu.shadow.enable && !smoothmenu.css3support){
							var shadowleft=header.istopheader? $targetul.offset().left+ddsmoothmenu.shadow.offsetx : menuleft
							var shadowtop=header.istopheader?$targetul.offset().top+smoothmenu.shadow.offsety : header._shadowoffset.y
							if (!header.istopheader && ddsmoothmenu.detectwebkit){ //in WebKit browsers, restore shadow's opacity to full
								header.$shadow.css({opacity:1})
							}
							header.$shadow.css({overflow:'', width:header._dimensions.subulw+'px', left:shadowleft+'px', top:shadowtop+'px'}).animate({height:header._dimensions.subulh+'px'}, ddsmoothmenu.transition.overtime)
						}
					}
				}, ddsmoothmenu.showhidedelay.showdelay)
			},
			function(e){
				var $targetul=$subul
				var header=$curobj.get(0)
				clearTimeout($targetul.data('timers').showtimer)
				$targetul.data('timers').hidetimer=setTimeout(function(){
					$targetul.animate({height:'hide', opacity:'hide'}, ddsmoothmenu.transition.outtime)
					if (smoothmenu.shadow.enable && !smoothmenu.css3support){
						if (ddsmoothmenu.detectwebkit){ //in WebKit browsers, set first child shadow's opacity to 0, as 'overflow:hidden' doesn't work in them
							header.$shadow.children('div:eq(0)').css({opacity:0})
						}
						header.$shadow.css({overflow:'hidden'}).animate({height:0}, ddsmoothmenu.transition.outtime)
					}
				}, ddsmoothmenu.showhidedelay.hidedelay)
			}
		) //end hover
	}) //end $headers.each()
	$mainmenu.find('ul').css({display:'none', visibility:'visible'})
},

init:function(setting){
	if (typeof setting.customtheme=='object' && setting.customtheme.length==2){ //override default menu colors (default/hover) with custom set?
		var mainmenuid='#'+setting.mainmenuid
		var mainselector=(setting.orientation=='v')? mainmenuid : mainmenuid+', '+mainmenuid
		document.write('<style type="text/css">\n'
			+mainselector+' ul li a {background:'+setting.customtheme[0]+';}\n'
			+mainmenuid+' ul li a:hover {background:'+setting.customtheme[1]+';}\n'
		+'</style>')
	}
	this.shadow.enable=(document.all && !window.XMLHttpRequest)? false : this.shadow.enable //in IE6, always disable shadow
	jQuery(document).ready(function($){ //ajax menu?
		if (typeof setting.contentsource=='object'){ //if external ajax menu
			ddsmoothmenu.getajaxmenu($, setting)
		}
		else{ //else if markup menu
			ddsmoothmenu.buildmenu($, setting)
		}
	})
}

} //end ddsmoothmenu variable

