/* ===========================================================================
   KEYBROKER
   Generic JavaScript (depends on jQuery)
   By Starring
============================================================================*/

var Keybroker = {}; // Set up a namespace

/* Add functionality to print links */
$.fn.printLink = function() {
  return this.each(function() {
    $(this).click(function() {
      window.print();
      return false;
    });
  });
}

/* Drop down menu functionality */
$.fn.dropDownMenu = function() {
  var event = {
    show: function(id) {
      items.filter('.current').removeClass('current').addClass('current_');
      menus[id].item.addClass('active');
      if (menus[id].menu.length) menus[id].item.addClass('menu_active');
    },
    hide: function(id) {
      items.filter('.current_').removeClass('current_').addClass('current');
      menus[id].item.removeClass('active').removeClass('menu_active');
    }
  }

  if (this.length > 1) return this;

  var menus = Array();
  var items = this.find('> li');

  items.find('> a, > span').each(function(id) {
    var self = $(this);

    menus[id] = {};
    menus[id].item = self.parents('li:first');
    menus[id].menu = menus[id].item.find('ul:first');

    $(window).bind('load', function() {
      var elm = menus[id].item.get(0);
      var offset = self.offset();
      // menus[id].menu.css('left', elm.offsetLeft);
      menus[id].menu.css('top', elm.offsetTop+elm.offsetHeight+14);
    });

    self.add(menus[id].menu)
      .mouseover(function() {
        event.show(id);
        return false;
      })
      .mouseout(function() {
        event.hide(id);
        return false;
      })
      .focus(function() {
        event.show(id);
        return false;
      })
      .blur(function() {
        event.hide(id);
        return false;
      });
  });

  return this;
}


/* CampaignControl™ panel animation */
$.fn.ccLogin = function(settings) {
  var settings = $.extend({
    linkPath: '#cc_loginlink a:first'
  }, settings);

  var showHidePanel = function() {
    link.toggleClass('active');
    panel.animate({ height: 'toggle' }, 400, 'easeOutExpo', function() {
      if (panel.is(':visible')) panel.find('input:first').trigger('focus');
    });
  }

  var panel = $(this);
  var link = $(settings.linkPath);

  link.click(function() {
    showHidePanel();
    return false;
  });

  panel.hide();

  return this;
}


/* Show the header Flash on the Start page */
$.fn.loadStartFlash = function() {
	var link = this;
	var testLink = $('div#content-wrapper');
	var panel = this.parents('div:first');
	
	//console.log(panel);
	
	var flashSrc = this.attr('href');
	
	//console.log('flash src: '+flashSrc);
	
	/*
	var animatePanel = function() {
	  	panel.animate({ width: '100%' }, 600, null);
	}
	var fadeLink = function() {
	  	link.animate({ opacity: '0' }, 400);
	  //link.hide();
	}
	*/
	
    
    //console.log('loading small flash');
  	// load the flash clicker
	

  link.click(function() {
    return false;
  });

  return this;
}

var loadSecondFlash = function() {
	var panel = $('div#content-header div.col2');
	var link = $('div.col2 a:first');
	
	var altImage = $('div.col2 div.alt a>img');
	altImage.parent().css('display', 'block');

	var img = $('div#content-header div.col2 img');
	img.css('opacity', '0');	
	
	unloadSmallFlash();

	panel.animate({ width: '100%' }, 600, null, function(){
	    panel.flash({
	      src: '../public_flash/kb_animation.swf',
	      width: 930,
	      height: 270,
	      wmode: 'transparent',
	      flashvars: {'xmlPath': xmlPaths[Keybroker.currentLang]}		
	    });
	});
}

var unloadSmallFlash = function() {

	var link = $('#content-header.start .col2 a:first');
	var panel = $('#content-header.start .col2');
	
	// Unload the Flash
	panel.find('embed,object').remove();
}

/* A function for returning the start flash area to normal,
   written to be called externally (e.g. from a Flash movie) */
var unloadStartFlash = function() {
  var link = $('#content-header.start .col2 a:first');
  var panel = $('#content-header.start .col2');

  // Unload the Flash
  panel.find('embed,object:first').remove();
  var alt = panel.find('.alt:first');
  var contents = alt.contents();
  panel.removeClass('flash-replaced').append(contents);
  alt.remove();

  link.css('opacity', '0');
  // Perform animation
  panel.animate({ width: '300px' }, 600, function() {
  	link.flash({
		src: '../public_flash/puff.swf',
		width: 300,
		height: 270,
		wmmode: 'transparent'
		
		});
  
  });
  link.animate({ opacity: '1' }, 400, function() {
  
  });

  // Rebind events
  $('#content-header.start a[rel=flash]').loadStartFlash();
}


/* Submit a form when the first select box is changed, hide any submit buttons */
$.fn.selectSubmit = function() {
  this.find('select:first').change(function() {
    $(this.form).trigger('submit');
  });
  this.find('input[type=submit],span.button,button').hide();

  return this;
}


/* Add a loader when a form is submitted */
$.fn.formLoader = function() {

  var forms = this;

  forms.bind('submit', function() {
    var form       = $(this);
    var formHeight = form.height();

    // Add the loader DIV
    var loaderBg = $('<div id="loader-bg" />');
    var loader   = $('<div id="loader" />');

    loader.hide();

    // Set loader height and position
    if ($.browser.msie) loaderBg.css('height', formHeight);
    loader.css('top', this.offsetTop+(formHeight/2)-50);

    // Insert the DOM elements
    form.append(loaderBg);
    form.after(loader);

    // Make fields readonly, transparent + show the loader
    form.find(':input, button').attr('readonly', 'readonly').trigger('blur');
    form.fadeTo('fast', 0.3);
    loader.fadeIn(100);
    /*if (form.attr('id') == 'contactForm') {
    	submitContactForm(form);
    	return false;
    }*/
  });

  return this;
}

/* Ugly code to remove buggy drupal empty p tag causing safari to 'repair it' */
var removeEmptyPTag = function() {
	var fieldset = $('div.col1 form>fieldset:first');
	var fieldsetClone = fieldset.clone();
	fieldset.empty();
	
	var firstP = fieldsetClone.find('p:first');
	// only remove elements without children
	if (firstP.children().length == 0) {
		firstP.remove();
	}
	fieldset.html(fieldsetClone.html());
}
/* submit form with ajax */
var submitContactForm = function(form) {
	//console.log(form.attr('action'));
	
	var url = form.attr('action');
	if(url == '') {
		url = window.location.href;
	}
	$.ajax({
		url: url,
		/*dataType: 'json',*/
        type: 'POST',
        data: $(form).serialize(),
		success: function(response) {
			//console.log('response: '+response);
			removeLoading();
			form.fadeTo('fast', 1);
			form.find(':input, button').removeAttr('readonly');
			form.before('<h2>Thank you for your application!</h2><p>We will respond as soon as possible.</p><iframe src="http://www.keybroker.com/gct.html" id="gct"></iframe>');
			form.remove();
		}
	});
	
}

var removeLoading = function() {
	
	var loader = $('div#loader');
	var loaderBg = $('div#loader-bg');
	loader.remove();
	loaderBg.remove();
	
}



/* Initialize the Google Map after the page has loaded: */
$(window).load(function() {
  var map = $('#map');
  if (!map.length) return false;

  var strLatLng = $('.col2_map .address').attr('title');
  if (!strLatLng) throw("Couldn't find a parseable Latitude/Longitude string!");
  strLatLng = strLatLng.replace(/\s/g, '');
  aryLatLng = strLatLng.split(",");
  if (aryLatLng.length != 2) throw("Couldn't parse Latitude/Longitude!");
  aryLatLng = Array(parseFloat(aryLatLng[0]), parseFloat(aryLatLng[1]));

  map.jmap('init', {
    mapShowjMapIcon: false,
    mapCenter: [aryLatLng[0],aryLatLng[1]],
    mapZoom: 15
  });
  map.jmap('addMarker', {
    pointLatLng: [aryLatLng[0],aryLatLng[1]]
  })
  
  
  
});


/* Run code on DOM ready */
$(function() {

  Keybroker.currentLang = $('div.wrapper>ul.countries>li.current>a').text();
  //console.log(Keybroker.currentLang);
  //console.log('xml path to load:'+xmlPaths[Keybroker.currentLang]);

  if (jQuery.browser.msie) $('img').attr('galleryimg', 'no');
  $('a[rel=print]').printLink();
  $('#toolbar ul li:first, #header ul li:first').addClass('first');
  $('#cc_login').ccLogin();
  $('#header > ul').dropDownMenu();
  $('#office_select_form').selectSubmit();
  $('#content-header.start a[rel=flash]').loadStartFlash();
  $('#content form').formLoader();
  $('#content h1').sifr({ font: '/sites/all/themes/mall/javascripts/metaplusmedium', textAlign: 'left' });
  
  
  
  removeEmptyPTag();
  
  $('.jqModal').click(function() {
	  $('#whyKeybrokerFlash').flash({
		  src: '../public_flash/kb_animation.swf',
		  width: 930,
		  height: 270,
		  flashvars: {'xmlPath': xmlPaths[Keybroker.currentLang]}
	  });
  });
  if ($('.jqModal').is('*') != false) {
  	$('#whyKeyBrokerFlashContainer').jqm();
  }
  var panel = $('#content-header.start .col2 a');
  panel.flash({
		src: '../public_flash/puff.swf',
		width: 300,
		height: 270,
		wmmode: 'transparent'
		
  });
  
  
  
});

/* Inject easing functions */
jQuery.extend(jQuery.easing, {
  // Animation equation originally by Robert Penner (www.robertpenner.com)
  easeOutExpo: function (x, t, b, c, d) {
    return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
  }
});

var xmlPaths = {
    'Svenska': 'public_flash/xml/data_sv.xml',
    'English': 'public_flash/xml/data_en.xml',
    'Dansk': 'public_flash/xml/data_dk.xml',
    'Deutsch': 'public_flash/xml/data_de.xml',
    'Francais': 'public_flash/xml/data_fr.xml',
    'Italiano': 'public_flash/xml/data_i.xml',
    'Norsk': 'public_flash/xml/data_no.xml',
    'Suomi': 'public_flash/xml/data_fi.xml'
};

