var path = "";
var sections = new Object();
var contacth = null;
var addthis_pub = 'planbz';
var pulsearray = [];
var activesection = null;

$(document).ready(function() {

	// main sections
	var mainnav = $('div.space').find('h1 a');
	var counter = 0;
	mainnav.each(function(){
		var status = true;
		var url = getRelativeURL($(this).attr('href'));
		var h1 = $(this).parent();
		h1.after('<div id="container'+counter+'" class="width"></div>');
		var container = $('div#container'+counter);
		container.append('<div id="subnav'+counter+'"></div>');
		var subnav = $('div#subnav'+counter);
		subnav.after('<div id="content'+counter+'" class="width"></div>');
		var content = $('div#content'+counter);
		var me = $(this);
		me.html('<span>'+me.html()+'</span>');
		content.hide();
		h1.addClass('active');
		sections[url.substring(1)] = new sectionObj(me,url,h1,container,subnav,content,status);
		
		
		
		counter++;
	});
	
	// logo
	$('a#branding-logo').click(function(me){
		me.preventDefault();
		sections['about-us'].me.trigger('click');
		return false;
	});
	
	// news items
	var newsnav = $('div.ad').find('h1 a');
	var ncnt = 0;
	newsnav.each(function()
	{
		$(this).html('<span style="font-weight:bold;">'+$(this).html()+'</span>');
		var url = getRelativeURL($(this).attr('href'));
		var h1 = $(this).parent();
		h1.after('<div id="newsbox'+ncnt+'"></div>');
		var newsbox = $('div#newsbox'+ncnt);
		newsbox.hide();
		$(this).attr('rel','closed');
		
		$(this).click(function()
		{
			obj = $(this);
			pulse(obj.find('span'),true);
			if (obj.attr('rel') == 'closed') {
				obj.attr('rel','transition');
				newsbox.load(path+'/dynamic.php?url='+url,function(data)
				{
					activateSlideshow(newsbox);
					obj.attr('rel','open');
					closeAndSetSection(obj);
					// instead of sliding down get the first image and animate the height
					newsbox.height(0);
					newsbox.css('display','block');
					var nh = 24+$(this).find('.ad-content').height() + parseInt($(this).find('.slideshow li').eq(0).attr('rel'));
					//setTimeout(function(){newsbox.animate({height: nh}, 200, function(){stoppulse(obj.find('span'));});},400);
					newsbox.animate({height: nh}, 400, function(){
						stoppulse(obj.find('span'));
					});
					//newsbox.slideDown(function(){
					//	stoppulse(obj.find('span'));
					//});
					h1.addClass('active');
				});
			} else if (obj.attr('rel') == 'open') {
				obj.attr('rel','transition');
				obj.attr('rel','closed');
				closeAndSetSection(null);
				newsbox.slideUp(function(){
						stoppulse(obj.find('span'));
					});
				newsbox.html();
				h1.removeClass('active');
				
			}
			return false;
		});
			
		ncnt++;
	});

	if (newsnav.length > 0) {
		newsnav.eq(0).trigger('click');
	}

});

function closeAndSetSection(which){

	if (activesection != null && activesection != which && which !=null) {
		// do your stuff
		activesection.trigger('click');
		activesection = which;
	} 
	
	/*else if (activesection == which) {
		activesection = null;
	} else */
	
	if (activesection == null || which == null) {
		activesection = which;
	}
	
}

function pulse(obj,init) {
	theobj = obj;
	if (init) {
		pulsearray[obj] = true;
	}
	if (pulsearray[obj] != null) {
		if ($.browser.msie) {
			// don't do anything with opacity
			if (theobj.css('color').indexOf('70') > -1 ||  theobj.css('color').indexOf('46') >  -1) {
				theobj.css('color','#9a9a9a');
				setTimeout(function(){pulse(theobj)},150);
			} else {
				theobj.css('color','#464646');
				setTimeout(function(){pulse(theobj)},150);
			}
		} else {
			//console.log('pulse');
			//console.log(theobj);
			if(theobj.css('color').indexOf('70') > -1 ||  theobj.css('color').indexOf('46') >  -1) {
				theobj.css('color','#9a9a9a');
				setTimeout(function(){pulse(theobj)},150);
			} else {
				theobj.css('color','#464646');
				setTimeout(function(){pulse(theobj)},150);
			}
		}
	}
}

function stoppulse(obj) {
	//console.log('stop');
	//console.log(obj);
	
	pulsearray[obj] = null;
	//console.log(pulsearray);
	obj.stop();
	theobj = obj;
		//setTimeout(function(){stoppulse(theobj)},320);
	obj.css('color','#464646');
	if (obj.parent().parent().parent().parent().hasClass('content-box')) {
	    if (obj.parent().parent().hasClass('active'))  {
		    obj.css('color','#ffffff');
		   } else {
		    obj.css('color','#464646');
		}
	}
	//console.log(obj.css('opacity'));
}


function loadContent(u,s) {
	// parse the url
	var url = u;
	var scroll = s;
	var url_parsed = url.split('/');
	var obj = sections[url_parsed[1]];
	//if (obj.content.css('display') != 'none') {
	//if (typeof(obj.me) == 'object') {
		pulse(obj.me.find('span'),true);
	//}	
	
	obj.content.slideUp('fast', function(){
		obj.content.attr('rel',url);
		obj.content.attr('role','busy');
		obj.content.load(path+'/dynamic.php?url='+url,function(data){
			if(obj.content.attr('rel') == url) {
				if (url.indexOf('&') == -1) {
					obj.makeActive(url);
				}
				// here process any links in the content area
				
				
				
				
				// experise keywords
				obj.content.find('p.cloud a').click(function(me){
					me.preventDefault();
					var url = getRelativeURL($(this).attr('href'));	
					loadContent(url);
					if(activesection.attr('href').indexOf('views') < 0) {
						//console.log(activesection);
						sections['plan-views'].me.trigger('click');
					}
					return false;
				});
			
				// slideshows
				activateSlideshow(obj.content);
				// newsboxactivateSlideshow(newsbox);
			
			
				// collapsable elements	
				obj.content.find('a.collapse').each(function(){
					//debug(url);
					//debug($(this));
					var myparent = $(this).parent();
					//var myparenth = myparent.height();
					if (myparent.parent().hasClass('about-box')) {
						$(this).attr('rel','closed');
						myparent.addClass('active');
						myparent.next().hide();
					} else {
						$(this).attr('rel','open');
					}
					$(this).click(function(me){
						debug('clicked '+contacth);
						me.preventDefault();
						if($(this).attr('rel') == 'open') {
							if (myparent.parent().parent().hasClass('contact-image')) {
								myparent.parent().animate({height:'26px'},200);
							} else {
								myparent.next().slideUp('fast');
								myparent.parent().css('paddingBottom',0);
							}
							myparent.addClass('active');
							$(this).attr('rel','closed');
						} else {
							if (myparent.parent().parent().hasClass('contact-image')) {
								myparent.parent().animate({height:contacth+'px'},200);
							} else {
								myparent.next().slideDown('fast');
								myparent.parent().css('paddingBottom','10px');
							}
							myparent.removeClass('active');
							$(this).attr('rel','open');
						}
						return false;
					});
				});
			
				
				// forms
				var requestform = obj.content.find('div.ask form');
				requestform.submit(function(){
					var action = getRelativeURL(requestform.attr('action'));
					var vars = requestform.serialize()+'&request=request&subscribe=Subscribe';
					requestform.parent().parent().find('div.error').remove();
					$.post(path+'/dynamic.php?url='+action,vars,function(data){
						//debug(data);
						var error = data.indexOf('<div class="ask error"><p>');
						var success = data.indexOf('success');
						if (error > -1) {
							var errorstr = data.substring(error);
							errorstr = errorstr.substring(0,errorstr.indexOf('</div>')+6);
							requestform.parent().after(errorstr);
						} else if (success > -1) {
							success = success+9;
							var successstr = data.substring(success);
							successstr = successstr.substring(0,successstr.indexOf('</p>')+4);
							requestform.parent().html(successstr);
							requestform.parent().addClass('success');
						}
						// handle successfull request
						
					});
					
					
					return false;
				});
			
				// pager views
				obj.content.find('div#paginator-views li a').click(function(me){
					me.preventDefault();
					var url = getRelativeURL($(this).attr('href'));	
					debug(url.replace("/dynamic.php?url=",""));
					loadContent(url.replace("/dynamic.php?url=",""));
					return false;
				});
		
			
			
				obj.content.slideDown(function(){
					obj.content.attr('role','click');
					stoppulse(obj.me.find('span'));
				});			
			
				contacth = obj.content.find('div.contact-image div.image-box').height();
				// views
				var views = obj.content.find('div.preview h1 a');
				
				views.each(function(){
					// first enable summary rollover
					var container = $(this).parent().parent().parent();
					//console.log(container);
					var url = getRelativeURL($(this).attr('href'));	
					var snip = container.find('.snip');
					var cont = container.find('div.content');
					var containerh = _convertPXtoValue(container.find('div.image-box').css('height'));
					
					$(this).html('<span>'+$(this).html()+'</span>')
					//debug(container.find('div.image-box'));
					//debug(containerh);
					
					snip.hide();
					var snipbutton = $(this).parent();
					debug(snipbutton.hasClass('active'));
					$(this).hover(function()
					{
					if ($(this).attr('rel') == 'closed')
						{
						snip.show();
						}
					},
					function()
					{
						snip.hide();
					});
				
					
					$(this).attr('rel','closed');

					// then open and close on click....
					// <div class="content">
					$(this).click(function(me){
						//debug('click');
						me.preventDefault();
						var obj = $(this);
						pulse(obj.find('span'),true);
						if ($(this).attr('rel') == 'closed') {	
							debug(cont);
							obj.attr('rel','transition');
							obj.parent().addClass('active');
							//container.append('<div class="content"></div>');
							//var cont = container.find('div.content');
							//content.show();
							// add content div
							cont.load(path+'/dynamic.php?url='+url,function(data){
								//obj.html(cont.height());
								var newheight = containerh + 17 + 1;
								
								var leftheight = 0;
								cont.find('div.content-main').each(function(){
									$(this).find('h2').each(function(){
										leftheight += ($(this).height());
										leftheight += _convertPXtoValue($(this).css('margin-bottom'));
										leftheight += _convertPXtoValue($(this).css('margin-top'));
									});
								
									$(this).find('p').each(function(){
										leftheight += ($(this).height());
										leftheight += _convertPXtoValue($(this).css('margin-bottom'));
										leftheight += _convertPXtoValue($(this).css('margin-top'));
									});
								
								
								});
								
								var rightheight = 0;
								cont.find('div.content-rel').each(function(){
									$(this).find('h2').each(function(){
										rightheight += ($(this).height());
										rightheight += _convertPXtoValue($(this).css('margin-bottom'));
										rightheight += _convertPXtoValue($(this).css('margin-top'));
									});
								
									$(this).find('h3').each(function(){
									    rightheight += ($(this).height());
										rightheight += _convertPXtoValue($(this).css('margin-bottom'));
										rightheight += _convertPXtoValue($(this).css('margin-top'));
									});
									
									
									$(this).find('li').each(function(){
									    rightheight += ($(this).height());
										rightheight += _convertPXtoValue($(this).css('margin-bottom'));
										rightheight += _convertPXtoValue($(this).css('margin-top'));
									});
								
									$(this).find('p').each(function(){
										rightheight += ($(this).height());
										rightheight += _convertPXtoValue($(this).css('margin-bottom'));
										rightheight += _convertPXtoValue($(this).css('margin-top'));
									});
								});
								if (rightheight > leftheight) {
									newheight += rightheight;
								} else {
									newheight += leftheight + 17;
								}
							
								container.height('115px');
								snip.hide();
								
								container.animate({height:newheight+'px'},500,function(){
									//container.removeClass('preview');
									stoppulse(obj.find('span'));
								});
								//content.slideDown();
								obj.attr('rel','open');
								
							
								
								// parse topics
								cont.find('ul.topicsincontent li a').click(function(me){
									me.preventDefault();
									var url = getRelativeURL($(this).attr('href'));	
									loadContent(url,true);
									return false;
								});
								
							});
							
						} else if ($(this).attr('rel') == 'open') {
							obj.attr('rel','transition');
							obj.parent().removeClass('active');
							container.animate({height:'115px'},500,function(){
								obj.attr('rel','closed');
								stoppulse(obj.find('span'));
								cont.html();
							});
							
						}
						// load content
						
						// take off preview class
						
							
					
					
						return false;
					});
				
				});
			
			
			
			
			
				// if scroll is set to tru we want to scroll to the views section	
				if (scroll) {
					var targetOffset = sections['plan-views'].me.offset().top;
					debug(targetOffset);
					debug(sections['about-us'].me.offset().top);
					var bodyOffset = $('html').scrollTop() == 0 ? $('body').scrollTop() : $('html').scrollTop();
					debug(bodyOffset);
					//if ((bodyOffset - targetOffset) > 1) {
					$('html,body').animate({scrollTop: targetOffset}, 1000);
					//}
				}
				
				
			}
		});		
		
		
		
	});
	//}

}

function _convertPXtoValue(string) {
	if (string == 'auto') {
	    return -1;
	} else {
	    string = string.substring(0,string.length-2);
	    return parseInt(string);
    }
}

function activateSlideshow(context) {
	var slideshow = context.find('div.slideshow');
	//slideshow.addClass('width');
	//slideshow.append('<div class="width"></div>');
	var slideshowlinks = slideshow.find('li a');
	//var slideshowcontent = slideshow.find('div');
	var slcnt = 0;
	slideshowlinks.each(function(){
		var url = getRelativeURL($(this).attr('href'));	
		$(this).attr('rel',slcnt);
		if (slcnt == 0) {
			$.get(path+'/dynamic.php?url='+url,function(data){
				var imagedata = data.split(',');
				slideshow.css("background-image","url('"+imagedata[0]+"')");
				if (slideshow.height() != imagedata[1]) {
					slideshow.animate({height: imagedata[1]}, 200);
				}
				//slideshow.height(imagedata[1]+'px');
			});
			slideshow.attr('rel',slcnt);
			$(this).parent().addClass('active');
		}
		$(this).click(function(me){
			me.preventDefault();
			var myrel = $(this).attr('rel');
			if (myrel != slideshow.attr('rel')) {
				var url = getRelativeURL($(this).attr('href'));	
				$.get(path+'/dynamic.php?url='+url,function(data){
					var imagedata = data.split(',');
					slideshow.css("background-image","url('"+imagedata[0]+"')");
					debug(slideshow.height());
					if (slideshow.height() != imagedata[1]) {
						slideshow.animate({height: imagedata[1]}, 200);
					}
					//slideshow.height(imagedata[1]+'px');				
				});
				slideshowlinks.eq(slideshow.attr('rel')).parent().removeClass('active');
				slideshow.attr('rel',myrel);
				$(this).parent().addClass('active');
			}
			return false;
		});
		slcnt++;
	});
	

}


function getRelativeURL(url) {
	if (url.indexOf(path) != -1) {
		url = url.substring(url.indexOf(path)+path.length);
	}

	url = url.replace('http://www.plan.bz','');
	url = url.replace('http://plan.bz','');

	return url;
}


function debug(what){
	/*if(window.console && window.console.firebug){
		console.log(what);
	}	
	else{
		alert(what);
	}*/
}


/* section object code */
function sectionObj(me,url,h1,container,subnav,content,status) {
	this.me = me;
	this.url = url;
	this.h1 = h1;
	this.container = container;
	this.subnav = subnav;
	this.content = content;
	this.status = status;
	this.subnavobj = new Object();
	this.subnavobjk = [];
	this.active = null;
	this.init();
	
	return this;
	
}

sectionObj.prototype.makeActive = function(url) {
	debug(this.h1);
	debug(this.subnavobj);
	if (this.active != null) {
		this.subnavobj[this.active].me.parent().removeClass('active');
	}
	if (this.active != url) {
		this.subnavobj[url].me.parent().addClass('active');
		this.active = url;
	}
}

sectionObj.prototype.makeFirstActive = function() {
	loadContent(this.subnavobj[this.subnavobjk[0]].url);
}

sectionObj.prototype.init = function() {
	var obj = this;
	// loading the subnav
	obj.container.hide();
	obj.subnav.load(path+'/dynamic.php?url='+obj.url,function(data){
	
		obj.subnav.find('li a').each(function(){
			var url = getRelativeURL($(this).attr('href'));	
			obj.subnavobj[url] = {me:$(this),url:url};
			obj.subnavobjk.push(url);
			$(this).click(function(me){
				me.preventDefault();
				if (obj.content.attr('role') != 'busy')	{
					
					/// check position of this if it's very low down in the viewport the scroll otherwise don't
						if (($(window).height() - obj.content.offset().top) > 90) {
							loadContent(url);
						} else {
							loadContent(url,true);
						}
				}
				return false;
			});
			
		});
		
		obj.container.slideUp();
		obj.h1.removeClass('active');
		obj.status = false;
		
		//debug(obj.subnavobj);
		// we need to load the first page
		/*var url = getRelativeURL(obj.subnav.find('li a').eq(0).attr('href'));
		obj.content.load(path+'/dynamic.php?url='+url,function(data){
			obj.content.slideDown();
			// here process any links in the content area
		});*/
	
		// here we hijack the links for the incoming subnav
		/*obj.subnav.find('li a').click(function(me){
			me.preventDefault();
			var url = getRelativeURL($(this).attr('href'));
			obj.content.slideUp();
			obj.content.load(path+'/dynamic.php?url='+url,function(data){
				obj.content.slideDown();
				// here process any links in the content area
			
			});
			
			return false;
		});*/
	obj.makeFirstActive();	
	});
	
	obj.me.click(function(me){
			me.preventDefault();
			if (obj.status) {
				obj.container.slideUp();
				obj.h1.removeClass('active');
				obj.status = false;
				closeAndSetSection(null);
			} else {
				closeAndSetSection(obj.me);
				obj.container.slideDown();
				obj.status = true;
				obj.h1.addClass('active');
				
			}
			
			
			return false;
		});
		
}







