if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}

/* Older browsers has no sessionStorage so we have to initialise sessionStorage variable
 * to avoid variable undefined errors
*/ 
if (!window.sessionStorage || typeof window.sessionStorage == 'undefined' || !sessionStorage || typeof sessionStorage == 'undefined'){ 
	sessionStorage = [];
}
/* compatibility fixes end */


/* initialising variables */
var mainPages = {
		'uusi_verkkopalvelu': {
			'slot': 196, 
			'lang': 'fi', 
			'channel': 'www' 
		},
		'nykyisen_palvelun_kehittaminen': {
			'slot': 197, 
			'lang': 'fi', 
			'channel': 'www' 			
		},
		'minulla_on_idea': {
			'slot': 198, 
			'lang': 'fi', 
			'channel': 'www' 			
		},
		'en_oikein_tieda': {
			'slot': 199, 
			'lang': 'fi', 
			'channel': 'www' 			
		} 
}

/* redirecting to the web2.5 version */

var loc = ''+ window.location;
var locArr = loc.split('/');

// remove http and empty value at the begining of the array
locArr = locArr.slice('2');

/* are we in dev or production site... */
var redirKey;
if (locArr[1].indexOf('p4_poutapilvi') >= 0 ) {
	redirKey = 2;
} else {
	redirKey = 1;
}

if (typeof mainPages[locArr[redirKey]] != 'undefined') {	
	var start = locArr.slice(0, redirKey);
	var end = locArr.slice(redirKey);
	var url = 'http://'+start.join('/')+'/#'+end.join('/');
	//window.location = url;
}

var mainPageData = false;

var SKIP_CACHING = true;
var P2011_MODE = 'production';
var pageLoad = true;

/* Poutapilvi2011 constructor */
function Poutapilvi2011() {

	var sliderData = false;
	var currentSub = 'root';
	var sliderTransformationOn = false;
	
	this.slideQueue = false;

	this.hoveringOn = 0;
	this.sub = new Array();
	this.currentMain = 'root';
	
	/* privileged methods for accessing private variables etc */
	this.getSliderData = function() {
		return sliderData;
	}
	
	this.setSliderData = function(data) {
		sliderData = data;
	}
		
	this.getCurrentMain = function() {
		return currentMain;
	}
	
	this.setCurrentMain = function(main) {
		currentMain = main;
	}
	this.getCurrentSub = function() {
		return currentSub;
	}
	
	this.setCurrentSub = function(value) {
		currentSub = value;
	}
			
	this.sliderTransformationOn = function(val) {
		if (val!=undefined) {
			sliderTransformationOn = val;
			return false;
		} else {
			return sliderTransformationOn;
		}
	}
	
	this.clearSelection = function(sub) {
		var obj = this;
		$.each(sub, function(index, selection) {
			obj.removeSelection(selection);
		});
	}
	
	this.getMainPageDataByHash = function(hash) {
		if (!mainPageData) {
			var postData = '';
			$.each(mainPages, function(index, item){
				postData += 'slot['+index+']='+item.slot+'&';
			});
	
			$.ajax({
				url: './json/getMainPageData.phtml',
				data: postData,
				dataType: 'json',
				async: false,
				type: 'POST',
				context: this,
				success: jQuery.proxy(function(json) {
					sessionStorage.mainPageImages = json;
					mainPageData = json;
				}, this)
			});
		}
		this.debug('hash', hash);
		for (i in mainPageData) {
			if (mainPageData[i].hash == hash) {
				return mainPageData[i];
			}
		}	
	}

	this.debug = function(context, msg) {
		if (P2011_MODE == 'production' ) {
			return;
		}
		
		if (typeof console !== 'undefined') {
			console.log(context+': '+msg);
		}
		
	}
}

Poutapilvi2011.prototype = {
		handleMainPageData: function(json) {
			this.setSliderData(json);
			if (pageLoad) {
				$('#item-1 .item_text').html(json[0].topText);
				$('#item-1 .item_image').html(json[0].topImage);
				$('#item-2 .item_image').html(json[1].topImage);
				$('#item-3 .item_image').html(json[json.length-1].topImage);						
			} else {
				if (typeof this.currentMain != 'undefined') {
					this.slideSliderTo(this.hoveringOn);
				}
			}
		},
		init: function(hash) {
			var selectedSubs = this.sub;
			this.sub = [];
			this.debug('currentMain', this.currentMain);
			if (hash && hash != 'root') {
				var mainHash = hash.split('/').shift();
				
				if (mainHash == 'error_message') {
					//alert('eeee');
					return;
				}
				/* redirect faulty hashs to the frontpage */
				if (typeof mainPages[mainHash] == 'undefined') {
					window.location = './';
					
					//alert(mainHash);
					return;
				} 

				var subHashes = hash.split('/').pop().split(',');
				if (subHashes[0] == mainHash || subHashes[0] == '') {
					subHashes = [];
				}
				var mainChange = true;
				var processSubs = false;
				
				this.debug('mainHash', mainHash);
				
				if (subHashes.length>0) {
					this.debug('subs', 'process please.');
					processSubs = true;
					
					$.each(subHashes, jQuery.proxy(function(index, value){
						if (value!='') {
							this.sub.push(value);
						}
					}, this));
				}	
				
				if (this.currentMain == mainHash) {
					this.debug('main', 'no changes here...');
					mainChange = false;
					
				} else {
					this.clearSelection(selectedSubs);
					var $mainMenuItem = $('#link-'+mainHash); 

					if (!IS_MOBILE) {
						$mainMenuItem.data('raphael').buttonClick();
					}
					
					var useCache = true;

					if (SKIP_CACHING) {
						useCache = false;
					} else {
						if (typeof sessionStorage[mainHash] === 'string') {
							var cacheData = JSON.parse(sessionStorage[mainHash]);
							if (typeof cacheData !== 'object') {
								useCache = false;
							}
						} else {
							useCache = false;
						}
					}
					
					var noSlide = false;
					if (typeof this.currentMain == 'undefined' || this.currentMain == 'root') {
						noSlide = true;
					}
					if (useCache) { 
						if (!$('#main_nav_sub').is(":hidden")) {
							var p2011 = this;
							$('#main_nav_sub').fadeOut().last().queue(function () {
								$(this).dequeue();
								$('#main_nav_sub').empty();
								p2011.getSubPageLinksAndImages(cacheData, mainHash);
								$('#main_nav_sub').fadeIn();
							});
						} else {
							this.getSubPageLinksAndImages(cacheData, mainHash);
							$('#main_nav_sub').fadeIn();
						}
					} else {
						$.ajax({
							url: './json/getSubPages.phtml',
							data: {slot: mainPages[mainHash].slot},
							dataType: 'json',
							success: jQuery.proxy(function(json){
								sessionStorage[mainHash] =  JSON.stringify(json);
								if (!$('#main_nav_sub').is(":hidden")) {
									var p2011 = this;
									$('#main_nav_sub').fadeOut().last().queue(function () {
										$(this).dequeue();
										$('#main_nav_sub').empty();
										p2011.getSubPageLinksAndImages(json, mainHash, noSlide);
										$('#main_nav_sub').fadeIn();
									});
								} else {
									this.getSubPageLinksAndImages(json, mainHash, noSlide);
									$('#main_nav_sub').fadeIn();
								}
							}, this)
						});
					}
				}
	
				this.currentMain = mainHash
			} else {
				this.clearSelection(selectedSubs);

				$('#main_nav_sub').fadeOut().last().queue(function () {
					$(this).dequeue();
					$('#main_nav_sub').empty();
				});
				
				var postData = '';
				$.each(mainPages, function(index, item){
					postData += 'slot['+index+']='+item.slot+'&';
				});
				
				if (mainPageData) {
					this.handleMainPageData(mainPageData);	
				} else {
					$.ajax({
						url: './json/getMainPageData.phtml',
						data: postData,
						dataType: 'json',
						type: 'POST',
						context: this,
						success: jQuery.proxy(function(json) {
							sessionStorage.mainPageImages = json;
							mainPageData = json;
							this.handleMainPageData(json);	
						}, this)
					});
				}
				this.currentMain = mainHash
			}
			pageLoad = false;
		},
		getSubPageLinksAndImages: function(json, main, noSlide) {
			
			var countter = 0;
			mainPages[main].subPages = json;
			this.setSliderData(json);
			
			var menuTopLineWidth = 0;
			switch (main) {
				case 'uusi_verkkopalvelu': 
					menuTopLineWidth = 123;
				break;
				case 'nykyisen_palvelun_kehittaminen':
					menuTopLineWidth = 359;					
				break;
				case 'minulla_on_idea':
					menuTopLineWidth = 595;
				break;
				case 'en_oikein_tieda': 
					menuTopLineWidth =  831;
					break;
			} 
			
			$('#main_nav_sub').append($('<div style="background-color: #fff; position: relative; width:'+menuTopLineWidth+'px; height: 2px; top: -6px; left: -7px; z-index:100"></div>'));

			$.each(json, jQuery.proxy(function(index, value) {
				var $subButton = $('<span class="main_nav_sub_item" id="sub_nav_button_'+value.slot+'"><a   href="?s='+value.slot+'&l=fi&c=www">'+value.title+'</a></span> ');						
				this.debug(value.slot, this.sub.indexOf(value.slot));
				this.debug('value.slot', value.slot);
				if (this.sub.indexOf(value.slot) > -1) {
					this.debug('sub.indexOf', 'klikattu...'+value.slot);
					$subButton.addClass('selected_sub_nav');
					this.addPageToMain(value.mainContent, value.slot);				
				}

				$subButton.bind('click', {'slot': value.slot, obj: this, html: value.mainContent}, function(event) {
					event.preventDefault();
					event.data.obj.debug('kliks', 'yeah');
					if ($(this).hasClass('selected_sub_nav')) {
						event.data.obj.removeSelection(event.data.slot);
						event.data.obj.debug('kliks', 'removed..?');
					} else {
						if (event.data.obj.sub.indexOf(event.data.slot) == -1) {
							event.data.obj.debug('kliks', 'index==-1');
							event.data.obj.sub.push(event.data.slot);
							$(this).addClass('selected_sub_nav');
							event.data.obj.addPageToMain(event.data.html, event.data.slot);
						}
					}	
					event.data.obj.debug('eventData', event.data.obj.sub);
					event.data.obj.debug('fooo', main+'/'+event.data.obj.sub.join(','));

					$.history.load(main+'/'+event.data.obj.sub.join(','));
					return false;
				});
			
				if((!navigator.userAgent.match(/iPhone/i)) && (!navigator.userAgent.match(/iP[oa]d/i))) {
					$subButton.bind('mouseover', {'count': countter, obj: this}, function(event) {
						event.data.obj.hoveringOn = event.data.count;
						event.data.obj.slideSliderTo(event.data.count);
					});
				}
				$('#main_nav_sub').append($subButton);
				countter++;		
			}, this));
		
			if (!noSlide) {
				this.slideSliderTo(main, true);
			}
		},
		
	addPageToMain:function(html, page) {
		this.debug('addPageToMain', page);
		if ($(window).scrollTop() <= 300)
			$('html, body').animate({"scrollTop": 300});

		var $container = $('#frontpage_container');
		$elem = $(html);
		$elem.css({'opacity': 0});
		$container.prepend($elem);
		
		var height = $elem.css('height');
		this.debug('HEIGHT', height);
		$elem.css({'height': 0});
		$elem.animate({'opacity':1, 'height': height}, 500);
		
		$($elem).find('.move').click(function () {
			$('html, body').animate({"scrollTop": 0});
		});
	},
		
	removeSelection: function(slot) {
			this.debug('removeSelection',slot);
			var $button = $('#sub_nav_button_'+slot)
			$button.removeClass('selected_sub_nav');
			
			var thisIndex = this.sub.indexOf(slot);
			
			if (this.sub[thisIndex] != undefined) {
				this.sub.splice(thisIndex, 1);
				this.debug('splice', this.sub);
			}
			
			var $contentItem = $('#contentItem_'+slot);
			$contentItem.animate({'height': '0px', 'opacity': 0}, 500, function(){
				$(this).remove();
			});	
	},
		
		
	slideSliderTo:function(nth, force) {
		this.debug('slideSliderTo');
		if (!this.getCurrentSub()) {
			this.setCurrentSub(this.currentMain+':0');
		}
		
		
		if (this.sliderTransformationOn() == true) {
			this.debug('set slideQueue', this.slideQueue);

			this.slideQueue = nth;
		} 

		if ((this.sliderTransformationOn() == true || this.getCurrentSub()==this.currentMain+':'+nth) && !force) {
			return;
		}
		
		this.sliderTransformationOn(true);
		this.setCurrentSub(this.currentMain+':'+nth);
		var subPages = this.getSliderData();
		
		if (!subPages) {
			this.sliderTransformationOn(false);
			return;
		}
		
		var setMain = false;
		var  mainD; 
		if (typeof nth == 'string') {
			setMain = true;
			mainD = this.getMainPageDataByHash(nth);
			nth = 0;			
		}
			
		if (!subPages[2]) {
			subPages[2] = {topText: '', topImage: '<img alt="" class="" src="files/970/955x338/poutapilvi.jpg">'};
		}
		if (!subPages[1]) {
			subPages[1] = {topText: '', topImage: '<img alt="" class="" src="files/970/955x338/poutapilvi.jpg">'};
		}
		if (!subPages[0]) {
			subPages[0] = {topText: '', topImage: '<img alt="" class="" src="files/970/955x338/poutapilvi.jpg">'};
		}
				
		var subPageCount = 	subPages.length;
		var image3Count = false;
		var image2Count = false;
	
		if (nth-1 < 0) {
			image3Count = subPageCount-1;
			image2Count = nth+1;
			
		} else if(subPageCount <= nth+1) {
			image3Count = nth-1;
			image2Count = 0;		
		} else {
			image3Count = nth-1;
			image2Count = nth+1;		
		}
	
		var $text1 		= $('#item-1 .item_text');
		var $image1 	= $('#item-1 .item_image img:first');
		var $image1Wrap = $('#item-1 .item_image');
		var $image2 	= $('#item-2 .item_image img:first');
		var $image2Wrap = $('#item-2 .item_image');
		var $image3 	= $('#item-3 .item_image img:first');
		var $image3Wrap = $('#item-3 .item_image');
				
		if (typeof subPages[nth] == 'undefined') {
			nth = 0;
		}

		/* fade out old top texts and fade in new one */
		$text1.animate({'opacity': 0}, 100, function(){
			if (setMain) {				
				$text1.html(mainD.topText);
			} else {
				$text1.html(subPages[nth].topText);
			}
			$text1.animate({'opacity': 1}, 100);
		});
		
		if (subPages[nth].topImage == "") {
			$image1Replacement = $('<img alt="" class="" src="files/970/955x338/poutapilvi.jpg">');				
		} else {
			if (setMain) {
				$image1Replacement = $(mainD.topImage);
			} else {
				$image1Replacement = $(subPages[nth].topImage);
			}
		}
		
		var obj = this;
		
		$image1.after($image1Replacement).animate({'marginLeft': '-600px'}, 400, function(){
			var count = $image1Wrap.find('img').length;
			$image1Wrap.children().not($image1Replacement).remove();

			obj.sliderTransformationOn(false);
			
			obj.debug('trasformation', 'complete');
			obj.debug('slieQueue', obj.slideQueue);
			if (obj.slideQueue !== false) {
				obj.debug('slideQueue', obj.slideQueue);
				obj.slideSliderTo(obj.slideQueue);
				obj.slideQueue = false;
			}
		});
	
		$image2Replacement = $(subPages[image2Count].topImage);
		$image2Wrap.append($image2Replacement);
		$image2.animate({'marginLeft': '-600px'}, 400, function(){
			var count = $image1Wrap.find('img').length;
			$image2Wrap.children().not($image2Replacement).remove();
		});
		
		
		
		if (typeof subPages[image3Count] == 'undefined') {			
			$image3Replacement = $('<img alt="" class="" src="files/970/955x338/poutapilvi.jpg">');				
		} else {
			$image3Replacement = $(subPages[image3Count].topImage);	
		}

		$image3Wrap.append($image3Replacement);
		$image3.animate({'marginLeft': '-600px'}, 400, function(){
			var count = $image1Wrap.find('img').length;			
			$image3Wrap.children().not($image3Replacement).remove();
		});
	}
};


var P2011 = new Poutapilvi2011();
var raphaelInstances = [];

/* DOM ready */
$(document).ready(function($) {	
	
	if (typeof IN_FRONTPAGE != 'undefined' && IN_FRONTPAGE) {
		/* crate svg-buttons and store button instance to element */
		
		if (!IS_MOBILE || navigator.userAgent.match(/iPhone/i)) {
			$('#link-uusi_verkkopalvelu').data('raphael', new createButton('link-uusi_verkkopalvelu', "TARVITSEN\nUUDEN\nVERKKOPALVELUN"));
			$('#link-nykyisen_palvelun_kehittaminen').data('raphael', new createButton('link-nykyisen_palvelun_kehittaminen', "HALUAN KEHITTÄÄ\nNYKYISTÄ\nVERKKOPALVELUA"));
			$('#link-minulla_on_idea').data('raphael', new createButton('link-minulla_on_idea', "IDEASTA\nVERKKOON"));
			$('#link-en_oikein_tieda').data('raphael', new createButton('link-en_oikein_tieda', "KARTOITA\nTARPEESI"));
		} 

		var currentPos = 0;

		/* initialising history */
		$.history.init(function(hash){
			P2011.init(hash);
		}, { unescape: ",/" });
		
		/* some events */
		$('.p4_mainbuttons').click(function (event) {
			
			event.preventDefault();
			
			$('html, body').animate({"scrollTop": 0});
			$('.main_selected').each(function(index) {
				if (!IS_MOBILE) {
					raphael = $(this).data('raphael');
					raphael.buttonClick();
				}
			});
			
			var element = $(this).attr('id').split('-').pop();
			if (P2011.currentMain == element) {
				P2011.currentMain = 'root';
				element = 'root';
			} 
	
			$.history.load(element);
			return false;
		});
		
		$('.removeContent_button').live('click', function() {
			var slot = $(this).attr('id').split('_').pop();
			P2011.removeSelection(slot);
			$.history.load(P2011.currentMain+'/'+P2011.sub.join(','));		
		});
	
		if((!navigator.userAgent.match(/iPhone/i)) && (!navigator.userAgent.match(/iP[oa]d/i))) {
	
			$('.p4_mainbuttons').bind('mouseover', function(event) {				
				if (P2011.currentMain && P2011.currentMain!='root') {
					return;
				}
				
				var index = $(".p4_mainbuttons").index(this);
				P2011.hoveringOn = index;
				P2011.slideSliderTo(index);
			});
		}
		
		
		
		/* scrolling ... */
		var topStyle = 1;
		 $(window).scroll(function (e) { 
			 var pos = $(window).scrollTop();
			 if (pos >= 250 && topStyle == 1) {
				 
				 /* adding half a second delay before activating the "sroll up" bar to avoid some anoying things to happen ...*/
				 var t =  setTimeout(function() {
					  if ($(window).scrollTop() >= 250 && topStyle == 1) {
						 topStyle = 2;

						 $('#bodywrapper').append($('<div id="topscroller"><div id="topscroller_arrow"></div></div>').hide());
						 $('#topscroller').fadeIn(300, function() {
							 if ($(window).scrollTop() < 250) {
								 $('#topscroller').fadeOut(300, function() {
									 $('#topscroller').remove();
								 });
 
							 }
						 });
					 }
				 }, 500);
			 } else if (pos < 250 && topStyle == 2) {
				 topStyle = 1;
				 $('#topscroller').fadeOut(300, function() {
					 $('#topscroller').remove();
				 });
			 }
		 });
	}
	
	$('#topscroller').live('mouseenter', function(){
		$('html, body').animate({"scrollTop": 0});
	});

	$('.subnavi li').hover(
		function() {
			if (!$(this).hasClass('selected')) {
				$(this).find('img').animate({
					top: '-40px'
				}, 100);
			}
		},
		function() {
			if (!$(this).hasClass('selected')) {
				$(this).find('img').animate({
					top: '-10px'
				}, 100);
			}
		}
	);
	
	$('li.contact_us_link').click(function(e) {
		e.preventDefault();
		if (typeof $.fancybox == 'undefined') {
			$.getScript('./js/jquery.fancybox-1.3.4.pack.js', function(data, textStatus) {
				showFancyboxForm();			
			});
		} else {
			showFancyboxForm();
		}
	
		return false;
	});

	
	$('div.content').each(function() {
		var contentId = $(this).attr('id');

		var images = $('<div></div>').addClass('lbox_items');

		$('div#' + contentId + ' div.content_image img ~ div.content_image_caption').each(function() {
			var caption = $(this).text();
			var captionHTML = $(this).html().replace('"', '&quot;');
			var image = $(this).parent().children('img').attr('src').match(/^files\/(\d+)\/(?:[^\/]+\/)?(.*)/i);

			if (image && image[1]) {
				var lbox_item = $('div#dummy_html div.lbox_item').clone();
				lbox_item.find('a').attr('href', 'files/' + image[1] + '/textsize/' + image[2]).attr('title', captionHTML);
				lbox_item.find('img').attr('src', 'files/' + image[1] + '/94/' + image[2]).attr('alt', caption).attr('title', caption);
				lbox_item.children('p.lbox_caption').text(caption);
				lbox_item.appendTo(images);
			}
			$(this).parent().remove();
		});

		$(images).find('a').lightBox({
			fixedNavigation: true,
			txtImage: 'Kuva',
			txtOf: '/'
		});
		images.appendTo('div#' + contentId);
	});
	
});

function showFancyboxForm() {
	$.fancybox({
		href: './json/getForm.php',
		onComplete: function() {
			var $form = $('#fancybox-content form');
			$form.attr('action', './ota_yhteytta');
			
			$form.submit(function(e){
				if ($form.find('.form_error').length > 0) {
					return;
				}
				e.preventDefault();

				/* $.serialize() method doesn't include submit button value 
				 * becouse form is not submitted by clicking submit button, 
				 * so we have to append pwd_form_submit to the query string manually
				 */

				$.post("./ota_yhteytta", $form.serialize()+'&pwd_form_submit=1', function() {
					$('#fancybox-content').html('<h2>Kiitos yhteydenotostasi!</h2>');
				});

				return false;
			}) 
		}
	});
}

