var IOS = new Object();
IOS.Global = new Object();

IOS.Global.PopupStyles = {
	"default": "toolbar=no,scrollbars=yes,menubar=yes"
}

// Default currency symbol
IOS.Global.currencySymbol = "EUR";
IOS.Global.productPreviewMode = "click";

// Register console functions if not provided by webkit or firebug
if (typeof(console) == 'undefined')
{
	var console = new Object();
}
if (typeof(console.log) == 'undefined')
{
	console.log = function(){};
}

IOS.Global.getUserPk = function()
{
	return jQuery.cookie("SfUserPk");
}

IOS.Global.decode_utf8 = function(str)
{
	return decodeURIComponent(escape(str));
}

IOS.Global.encode_utf8 = function(str)
{
	return unescape(encodeURIComponent(str));
}

/**
 * Sets the cart information in the header to the current information
 * stored inside the SfNcCartQuantity and SfNcCartTotal cookie.
 */
IOS.Global.setCartInfo = function()
{
	// Fetch the number of items as well as the sum from the cart cookie
	// and display it
	var $userbar = jQuery('.user-bar');
	var amount = jQuery.cookie('SfCartTotalQuantity');
	var sum = jQuery.cookie('SfCartTotal');
	if (amount != null)
	{
		jQuery('.amount', $userbar).text(jQuery.base64Decode(amount));
		jQuery('.sum', $userbar).text(jQuery.base64Decode(sum) + " " + IOS.Global.currencySymbol);
	}
}

IOS.Global.isLoggedIn = function()
{
	var login = jQuery.cookie('SfLogin');
	return login != null;
}

/**
 * Sets the welcome box in the header as well as the account links
 * in the footer.
 */
IOS.Global.setWelcomeBox = function()
{
	var username = jQuery.cookie('SfUserName');
	var login = jQuery.cookie('SfLogin');
	
	if (login != null)
	{
		var $loggedInBox = jQuery('.welcome-box .loggedIn');
		jQuery('.username', $loggedInBox).text(IOS.Global.decode_utf8(jQuery.base64Decode(username)));
		$loggedInBox.show();
		jQuery('.welcome-box .loggedOut').hide();
		jQuery('a.logonOff').attr('href', IOS.Global.logoutLink);
	}
	else
	{
		jQuery('a.logonOff').attr('href', IOS.Global.loginLink);
	}
}

/**
 * Fills the product history box in the footer.
 */
IOS.Global.setProductHistory = function()
{
	var history = jQuery.cookie('ProductHistory');
	
	if (history != null)
	{
		history = IOS.Global.decode_utf8(jQuery.base64Decode(history));
		jQuery(history.split("|")).each(function(idx){
			var match = this.match(/^"(.*)"=(.*)$/);
			jQuery('#footer .producthistory ul').append('<li><a href="' + match[2] + '">' + match[1] + '</a></li>');
		});
	}
}


/**
 * Registers popup events for all links with the class popup. The title of the 
 * popup is generated from the @title of the link tag. If a link also has a 
 * popup-(.*) class, $1 will be used to determine the popup style as defined
 * in the IOS.Global.PopupStyles object.
 */
IOS.Global.registerPopups = function()
{
	jQuery('a.popup').bind('click', function(ev)
	{
		ev.preventDefault();
		var styleName = "default";
		var classes = jQuery(this).attr("class").split(" ");
		jQuery.each(classes, function(klass){
			var result = this.match(/^popup-(.*)$/);
			if (result != null)
			{
				styleName = result[1];
			}
		});
		var style = IOS.Global.PopupStyles[styleName];
		window.open(jQuery(this).attr('href'), jQuery(this).attr('title'), style);
	});
}

IOS.Global.timeDifference = function(from, to)
{
	var diff = to.getTime() - from.getTime();
	return IOS.Global.formatDuration(diff)
}

IOS.Global.formatDuration = function(ms)
{
	var result = {
		days: 0, hours: 0, minutes: 0, seconds: 0, total: ms,
		toString: function()
		{
			return "" + this.days + " Tag" + (this.days != 1 ? 'e' : '') +' : '+ this.hours + (this.hours != 1 ? ' Stunden' : ' Stunde') + ' : ' + (this.minutes < 10 ? '0' : '') + this.minutes + (this.minutes != 1 ? ' Minuten ' : ' Minute ') + ' : ' + (this.seconds < 10 ? '0' : '') + this.seconds + (this.seconds != 1 ? ' Sekunden ' : ' Sekunde '); 
		}
	}
	result.days = Math.floor(ms / (1000*60*60*24));
	ms = ms % (1000*60*60*24);
	result.hours = Math.floor(ms / (1000*60*60));
	ms = ms % (1000*60*60);
	result.minutes = Math.floor(ms / (1000*60));
	ms = ms % (1000*60);
	result.seconds = Math.floor(ms / 1000);
	return result;	
}

IOS.Global.promotionTooltips = function()
{
	var refRegEx = /(^|\s+)ref-(.*)($|\s+)/;
	$('.price-info').each(function(){
		var classes = $(this).attr('class').replace("  ", " ").split(" ");
		var mo = refRegEx.exec($(this).attr('class'));
		if (mo != null)
		{
			var tip = $('#' + mo[2]);
			// Move tip right before </body> to get around overflow issues
			tip.appendTo($('body'));
			$(this).tooltip({tip:tip, opacity: 0.8, effect:'fade', relative: tip.hasClass("relative")});
		}
	});
}

IOS.Global.handleExternalLinks = function()
{
	$('a[rel=external]').addClass('external').bind('click', function(ev){
		ev.preventDefault();
		window.open($(this).attr('href'));
	});
}

/**
 * Inserts the session id into given link elements before the query string
 */
IOS.Global.insertSessionId = function(elems)
{
	var sessionId = jQuery.cookie('JSESSIONID');
	elems.each(function(idx, val){
		var href = $(this).attr('href');
		if (href != null)
		{
			if (href.indexOf('?') != -1)
			{
				$(this).attr('href', href.replace(/\?/, ';jsessionid=' + sessionId + '?'));
			}
			else
			{
				$(this).attr('href', href + ";jsessionid=" + sessionId);
			}
		}
	});
}

IOS.Global.flyoutFix = function()
{
	$('.nav-area #nav > li')
    .hover(function(){
        // close all open drop down lists
    	$('select').blur();
    })
}

IOS.Global.prepareCartButtons = function(){
    // change amount for cart
    $('.cart-hold').each(function(){
      var container = $(this);
      var prod = $('input[name=code]', container).val();
      var update_carturl = function(){
        var quantity = $('input[name=amount]', container).val();
        $('.btn', container).attr("href", "/c/cart/add?code=" + prod + "&amount=" + quantity);
      }
      update_carturl();
      $(".btn-up", container).bind('click', function(ev) {
  	    ev.preventDefault();
  	    var currentVal = parseInt($("input[name=amount]", container).val());
  	    if (currentVal != NaN && currentVal < 99) {
  	      $("input[name=amount]", container).val(currentVal + 1);
  	    }
  	    update_carturl();
  	  });
  	  $(".btn-down", container).bind('click', function(ev) {
  	    ev.preventDefault();
  	    var currentVal = parseInt($("input[name=amount]", container).val());
  	    if (currentVal != NaN && currentVal > 1) {
  	      $("input[name=amount]", container).val(currentVal - 1);
  	    }
  	    update_carturl();
  	  });
    });
}

IOS.Global.initProductPreview = function(mode){
   $('.zoom-productdetail').bind(mode, function(ev){
     ev.preventDefault();
     $($(this).attr('rel')).overlay({
       api: true,
       effect: 'apple'
     }).load();
   });
}

IOS.Global.init = function()
{
	IOS.Global.flyoutFix();
	IOS.Global.setCartInfo();
	IOS.Global.prepareCartButtons();
	IOS.Global.setWelcomeBox();
	IOS.Global.setProductHistory();
	IOS.Global.registerPopups();
	IOS.Global.promotionTooltips();
	IOS.Global.handleExternalLinks();
	IOS.Global.initProductPreview(IOS.Global.productPreviewMode);
	$('div.drop-down').bgiframe();
	if (IOS.Global.isLoggedIn())
	{
		$('.showOnLoggedIn').show();
		$('.showOnLoggedOut').hide();
	}
	else
	{
		$('.showOnLoggedIn').hide();
		$('.showOnLoggedOut').show();
	}
	$('.newsletter-bar form').each(function()
	{
		$(this).attr('action', $(this).attr('action') + '?redirect=' + window.location.pathname);
	});
	// Handle the menu mouseover via JavaScript thanks to strange ie8compat behaviour
	jQuery("#nav > li").each(function(elem){
		var container = this;
		jQuery("> a", this).bind('mouseenter', function(ev){
			jQuery(container).addClass("hover");
		});
		jQuery(container).bind('mouseleave', function(ev){
			var that = jQuery(ev.target);
			jQuery(this).removeClass("hover");
		});
	});
	
	IOS.Global.insertSessionId($('a.login'));
	// Move all overlays to the bottom of the site
	var body = $('body');
	$('.overlay').appendTo(body);
};

jQuery(document).ready(IOS.Global.init);


IOS.Global.overflowsHorizontally = function(elem)
{
    var original = elem.scrollLeft++;
    var result = elem.scrollLeft > original;
    elem.scrollLeft-=1;
    return result;
};

IOS.Global.overflowsVertically = function(elem){
    var original = elem.scrollTop++;
    var result = elem.scrollTop > original;
    elem.scrollTop-=1;
    return result;
};

IOS.Global.overflows = function(elem){
	return IOS.Global.overflowsHorizontally(elem) || IOS.Global.overflowsVertically(elem);
};

IOS.Global.autoResize = function(element)
{
	var fontsize = parseFloat(element.css('font-size'));
	element.css('font-size', fontsize*2);
	element.css('line-height', (fontsize*2) + 'px');
	
    element.css({overflow:'hidden'});
    var title = element[0];
    var i = 0;
    while(IOS.Global.overflows(title))
    {
    	if (i > 1000) break;
        var fontsize = parseFloat(element.css('font-size'));
        element.css('font-size', fontsize - 1);
        element.css('line-height', (fontsize - 1)+ 'px');
        i++;
    }
};

(function(){
	jQuery.fn.autoResize = function(){
		return this.each(function(){
			IOS.Global.autoResize(jQuery(this));
		});
	};
	
	jQuery.fn.flash = function(options){
	  var opts = {
	      'background': '#E8D94C',
	      'duration': 1200
	  };
	  opts = jQuery.extend(opts, options);
	  return jQuery(this).each(function(){
	    var oldBackground = jQuery(this).css('backgroundColor');
	    jQuery(this).css('backgroundColor', opts.background).animate({backgroundColor: oldBackground},
	        opts.duration);
	  });
	};
})();