var Grieg = {
	months: ['Januar', 'Februar', 'Mars', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Desember'],
	ansatte: new Array(),
  emner: new Array(),
	reports: new Array(),
	meetings: new Array(),
  tags: {},
  posts: {},
	map: null,
  init: function(page) {
		Cufon.replace('SPAN.flink')('#nav LI A');
		if (page == 'front') {

			$('.newcarousel').jCarouselLite({
				btnPrev: '.btnPrev',
				btnNext: '.btnNext',
				easing: 'easein',
				visible: 1,
				circular: false,
				btnGo: [".front_menu #fp1", ".front_menu #fp2", ".front_menu #fp3", ".front_menu #fp4", ".front_menu #fp5"]
			});

			$('#username').click(function() {
				if (this.value == "Brukernavn (E-post)") this.value = ''
				else this.select();
			});
			
			$('#username').blur(function() {
				if (this.value == '') this.value = "Brukernavn (E-post)";
			});
		}

		else if (page == 'ansatte') {
			$('#overlay').click(function() {
				Grieg.hideAnsatt(); 
			});
		}

		else if (page == 'kontor') {
			this.map = new google.maps.Map($('#map_canvas')[0], {
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });

      this.marker = new google.maps.Marker({
        map: this.map,
        title: "Grieg Investor"
      });

      this.infowindow = new google.maps.InfoWindow();
			var params = window.location.href.slice(window.location.href.indexOf('?') + 1);
			if (params.indexOf('#') > -1) {
				params = params.substr(params.indexOf('#')+1).split('#');
        if (params[0]) this.showKontor(params[0]);
      }
		}

		else if (page == 'fagbibliotek') {
			$('.fagintro').height($('#fagbib').height()-2);
			$('.fagintro div').css('margin-top', $('.fagintro').height()/2-20);
			$('#search').click(function() {
				if (this.value == "S\xf8k i fagbiblioteket") this.value = '';
				this.select();
			});

			$('#search').blur(function() {
				if (this.value == '') this.value = "S\xf8k i fagbiblioteket";
			});
		
			// Autoshow post if params in url...
			var params = window.location.href.slice(window.location.href.indexOf('?') + 1);
			if (params.indexOf('#') > -1) {
				params = params.substr(params.indexOf('#')+1).split('#');
				if (params[0]) this.getTag(params[0], params[1]);
			}
		}

		else if (page == 'minside') {
			$('#search').click(function() {
				if (this.value == "Hva leter du etter?") this.value = '';
				this.select();
			});

			$('#search').blur(function() {
				if (this.value == '') this.value = "Hva leter du etter?";
			});
		
			$("#select_reports").sexyCombo({
				changeCallback: $.proxy(this.onReportchange, this)
			});

			$("#select_meeting_q").sexyCombo({
				changeCallback: $.proxy(this.onMeetingchange, this)
			});
			
			$("#select_meeting_y").sexyCombo({
				changeCallback: $.proxy(this.onMeetingchange, this)
			});

			if ($('.select_group')) {
				var self = this;
				self.sg1 = true;
				$(".select_group").sexyCombo({
					changeCallback: function() {
						if ( typeof($("input[name=select_group__sexyComboHidden]")[0]) != 'undefined' ) {
							var value = $("input[name=select_group__sexyComboHidden]")[0].value;
							if (!self.sg1) document.location.href='/minside?gid='+value;
							if (self.sg1) self.sg1 = false;
						}
					}
				});
			}
		}

		this.posFooter();
		$(window).scroll(this.posFooter).resize(this.posFooter);
  },

	/* Fagbibliotek */  
  showPost: function(id) {
    var tag = this.tag;
    $('.fagartikkel H2').html(this.posts[id].title);
    if (this.posts[id].content.unescapeHtml() == null) {
    	$('.fagartikkel P').html(this.posts[id].content);
    } else {
    	$('.fagartikkel P').html(this.posts[id].content.unescapeHtml());
    }
    var html='';
    if (this.posts[id].attachments) {
      for (var i=0;i<this.posts[id].attachments.length;i++) {
        html += '<a href="' + this.posts[id].attachments[i].url + '" title=""><img src="/wp-content/themes/grieg/images/icon_pdf.png" title="Last ned PDF" class="icon_pdf" width="34" height="39" />Klikk for &aring; &aring;pne '+this.posts[id].attachments[i].title+'</a>';
      }
    }
    $('.fagartikkel DIV').html(html);
    $('.fagartikkel').show('normal');
  },
  
  showPosts: function(tag) {
    $('.fagintro, .search_result').hide();

    var h = $('.submenu2').height();
    for (var p=1;p<this.emner.length+1;p++) {
      if (this.emner[p-1] == decodeURIComponent(tag)) break;
    }

    var top = (48*p)-19;
    var html='<img class="arrow" src="/wp-content/themes/grieg/images/submenu_expand.png" style="top: '+top+'px;"/>';
    
    for (var i=0;i<this.tags[tag].length;i++) {
      var post = this.posts[this.tags[tag][i]];
      html += '<li><a href="#'+this.tag+'#'+post.id+'" onclick="Grieg.showPost('+post.id+');" title="' + post.title + '">' + post.title + '</a></li>';
    };

		$('.submenu2').html('<ul>'+html+'</ul>').show('normal');

		var mh = $('.submenu2 UL').height();
		if (mh < p*48+48) {
			$('.submenu2').height((p)*48+48);
		} else {
			$('.submenu2').height(mh);
		}

    $('.fagartikkel').hide();
    if (this.postid) this.showPost(this.postid);
  },
  
  gotTag: function(data) {
    this.tags[this.tag] = new Array();
    
    for (var i=0;i<data.posts.length;i++) {
      this.tags[this.tag].push(data.posts[i].id);
      this.posts[data.posts[i].id] = data.posts[i];
    }
    
    this.showPosts(this.tag);
  },

  getTag: function(tag, postid) {
    this.tag = tag;
    this.postid = postid;
    if (this.tags[this.tag]) {
      this.showPosts(this.tag);
    } else {
      $.getJSON('/', { json: 'get_tag_posts', count: 100, tag_slug: tag }, $.proxy(this.gotTag, this));
    }
  },

	/* Ansatte */
	showAnsatt: function(ID) {
		$('#overlay').height($(document).height());
		$('#overlay').fadeTo('normal', .8);
		$('.ansatt_popup DIV IMG.pic').attr('src', this.ansatte[ID].Picture);
		$('.ansatt_popup DIV H2').text(this.ansatte[ID].Navn);
		$('.ansatt_popup DIV H4').text(this.ansatte[ID].Stilling);

		var html = 'E-mail: <a href="mailto:' + this.ansatte[ID].Email + '">' + this.ansatte[ID].Email + '</a><br />';
		if (this.ansatte[ID].Dir != '') html += 'Dir: ' + this.ansatte[ID].Dir + '<br />';
		if (this.ansatte[ID].Mobil != '') html += 'Mobil: ' + this.ansatte[ID].Mobil;

		$('.ansatt_popup DIV P:first').html(html);
		$('.ansatt_popup DIV P#acontent').html(this.ansatte[ID].Content.unescapeHtml());
		
		$('.ansatt_popup').center();
		$('.ansatt_popup').fadeTo('normal', 1);
		return false;
	},

	hideAnsatt: function() {
		$('#overlay, .ansatt_popup').hide('fast');
	},

	/* Kontorer */
	showKontor: function(kontor) {
		var self = this;
		$('#overlay').height($(document).height());
		$('#overlay').fadeTo('normal', .8);
		$('#kontor_popup').center().show('normal', function() {
			var latlng;
			var infocontent = '<b>Grieg Investor</b><br>';

      switch (kontor) {
        case 'Oslo':
          latlng = new google.maps.LatLng(59.918599, 10.68648);
          infocontent += 'Karenslyst All\xe9 2, 8. etasje<br>Postbok 513 Sk&oslash;yen<br>0214 Oslo';
        break;
        case 'Bergen':
          latlng = new google.maps.LatLng(60.395742, 5.318863);
          infocontent += 'C. Sundts Gate 17<br>Postbok 234 Sentrum<br>5004 Bergen';
        break;
        case 'Trondheim':
          latlng = new google.maps.LatLng(63.430398, 10.398516);
          infocontent += 'Kongens gate 8<br>7011 Trondheim';
        break;
        case 'Stavanger':
          latlng = new google.maps.LatLng(58.974337,5.721388);
          infocontent += 'Borgermester Middelthonsgate 10<br>Postboks 144 Sentrum<br>4001 Stavanger';
        break;
      }

			google.maps.event.trigger(self.map, 'resize') 
			self.map.setCenter(latlng);
			self.map.setZoom(14);
			self.marker.setPosition(latlng);
			self.infowindow.setContent(infocontent);
			self.infowindow.open(self.map, self.marker);

		});

		$('#overlay').click(function() {
			Grieg.hideKontor(); 
		});

		return false;
	},

	hideKontor: function() {
		$('#overlay, #kontor_popup').hide('fast');
	},

	/* Min side */
	onMeetingchange: function() {
		var html = '', month, quarter, year;
		var quarters = {
			1: [1,2,3],
			2: [4,5,6],
			3: [7,8,9],
			4: [10,11,12]
		};

		if ( typeof($("input[name=select_meeting_y__sexyCombo]")[0]) != 'undefined' ) {
			year = $("input[name=select_meeting_y__sexyCombo]")[0].value;
		}

		if ( typeof($("input[name=select_meeting_q__sexyCombo]")[0]) != 'undefined' ) {
			quarter = $("input[name=select_meeting_q__sexyCombo]")[0].value.substr(0,1);
		}
		
		if ( typeof($("input[name=select_meeting_m__sexyCombo]")[0]) != 'undefined' ) {
			month = $("input[name=select_meeting_m__sexyCombo]")[0].value;
			for (var i=0;i<this.months.length;i++) {
				if (this.months[i] == month) {
					month = i+1;
					break;
				}
			}
		}

		if (quarter && year) {
			for (var i=0;i<this.meetings.length;i++) {
				if (this.meetings[i].year == year) {
					if (this.meetings[i].month == quarters[quarter][0] || this.meetings[i].month == quarters[quarter][1] || this.meetings[i].month == quarters[quarter][2] ) {
						html += '<li>' + this.meetings[i].date + ' - <strong>' + this.meetings[i].title + '</strong></li>';
					}
				}
			}
			$(".meetings").html(html);
		}
	},
	
	onReportchange: function() {
		var html = '', cnt=0, month;
		var year = $("input[name=select_reports__sexyCombo]")[0].value;
		
		for (var i=0;i<this.reports.length;i++) {
			var d = this.reports[i]['title'].split('.');
			if (d[2] == year) {
				cnt++;
				if (d[1] != month) {
					month = d[1];
					html += '<h4>' + this.months[parseInt(month)-1] + ' ' + year + '</h4>';
				}
				html += '<a href="/?file=' + this.reports[i]['id'] + '"><div onclick="document.location.href=\'/?file=' + this.reports[i]['id'] + '\'" class="report">' + this.reports[i]['t'] + '</div></a>';
				if (i<this.reports.length-1) {
					if (month != this.reports[i+1]['title'].split('.')[1]) {
						html += '<hr>';
					}
				}
			}
		}
		$('#reports_top A').text('Nyere rapporter fra ' + year);
		$('#reports_bottom A').text('Eldre rapporter fra ' + year);
		$('#reports_top').hide();
		$('#reports').html(html).scrollTo(0);

		if (cnt <=5) $('#reports_bottom').hide()
		else $('#reports_bottom').show();

		if ($('#reports_box').height() > $('#midcol').height()) {
			$('#reports').css({
				overflow: 'hidden',
				height: $('#midcol').height()-116
			});
		} else {
			$('#reports').height('auto');
		}
	},
	
	scrollReports: function(dir) {
		if (dir == 'down') {
			if ($('#reports_top:hidden')) {
				$('#reports_top').show();
				$('#reports').css('height', $('#midcol').height()-182);
			}

			$('#reports').scrollTo('+=390', 200, {
				easing: 'easein'
			});
		}
		else if (dir == 'up') {
			if ($('#reports').scrollTop() <= 390) {
				$('#reports_top').hide();
				$('#reports').css('height', $('#midcol').height()-116);
			}

			$('#reports').scrollTo('-=390', 200, {
				easing: 'easein'
			});
		}

		return false;
	},

	validateLogin: function() {
		var res=true;
		if ( $('#password')[0].value == '') {
			$('#password').css('border', '1px solid red');
			$('#password').focus();
			res=false;
		} else {
			$('#password').css('border', '');
		}
		if ( ($('#username')[0].value == 'Brukernavn (E-post)') || ($('#username')[0].value == '') ) {
			$('#username').css('border', '1px solid red').select().focus();
			res=false;
		} else {
			$('#username').css('border', '');
		}

		return res;
	},

	showSearchresult: function() {
		$('.search_result_overlay').center();
		$('#overlay').height($(document).height());

		$('#overlay').fadeTo('fast', .8);
	},

	signup: function() {
		$('h1').html('');
		$('.main').html('<iframe class="myiframe" frameborder="0" scrolling="no" src="https://web.questback.com/grieggroupresourcesas/grieginvestor_finansseminar/"></iframe>');
		return false;
	},

	posFooter: function() {
/*		var fh = $('.footer').position().top+$('.footer').height()+74;
		if ($(window).height() > fh) {
			$('.footer').css('position', 'absolute');   
			this.h = $(window).height();
		}
		if (this.h && $(window).height() < this.h) {
			$('.footer').css('position', 'static');
			this.h = null;
		}
*/

//		if($(document.body).height() < $(window).height()) {
//			$(".footer").css({position: "absolute",top:($(window).scrollTop()+$(window).height()-$(".footer").height())+"px"});
//		}
	}
};

String.prototype.unescapeHtml = function () {
	try {
		var temp = document.createElement("div");
	  temp.innerHTML = this;
	  var result = temp.childNodes[0].nodeValue;
	  temp.removeChild(temp.firstChild);
	  return result;
  } catch (err) {}
}
