//fix background image flicker for IE 6 
try {document.execCommand("BackgroundImageCache", false, true);} catch(err) {}

var FFMac = (navigator.userAgent.match(/mozilla.+mac/i) !=null);


/*	TODO:
	- move the global flag animating somewhere else?
*/
var animating = false;

//The addItemWidget
jQuery.fn.addItem = function(s) {
	
	if(animating == true) {
		return false;
	}
	
	// s is for 'settings'...
	//if the button sends a different url, use that for Ajax:
	s.url = s.url || $("#addItemWidget-form").attr("action");
	s.msg = s.msg || '';
	s.unit = s.unit || 'meter';
	s.amount = s.amount || 1;	
	var el = $(this);
	
	
	// Ajax call
	function add() {
		//BR: serialize() has a bug in jquery 1.1.3.1... using another function now. 
		var params = $("#addItemWidget *").fieldSerialize();

		//disable buttons and input fields to avoid adding too many items:
		$("#addItemWidget-btn").attr("disabled",true).css("opacity",0.25)
		$("#addItemWidget-amount").attr("disabled",true);
		$('#addItemWidget-close').css("display","none");
		
		//var params = $("#addItemWidget :input").serialize(); //$("#addItemWidget input[@type!=submit]").serialize();		
		//$.post(s.url, params, function(data){
		$.getJSON(s.url, params, function(data) {
			/* 
			the callback expects take 3 properties:
			msg: for the addItem box, 
			cartId: the id of the cart info receiver
			cartMsg: the actual string being read into #cartId.
			*/

			if ($('#addItemWidget-notice').length==0) {
				//add the notice element to the DOM
				$("body").append('<div id="addItemWidget-notice"><p>'+data.msg+'</p></div>')
			} else {
				$("#addItemWidget-notice").html('<p>'+data.msg+'</p>');
			}
			
			//update cart Text
			$("#"+data.cartId).html(data.cartMsg);
			
			//show, then hide, the "item added"-notice:
			var aiw = $("#addItemWidget");
			var notice = $("#addItemWidget-notice");
			notice.css(aiw.offset()).width(aiw.width()).height(aiw.height()).show();
			aiw.hide()
			
			setTimeout(function(){
				if (!FFMac){
					notice.animate({opacity:"hide",height: 'hide'}, 300,"easein");
				} else {
					notice.animate({height: 'hide'}, 200,"easein");
				}
			}, 1000);
			return false;
		});
		return false;
	}

	//render the needed markup if it doesn't exist
	function renderMarkup() {
		$("body").append('<div id="addItemWidget"><div id="addItemWidget-inner"><form id="addItemWidget-form" action="' + s.url + '" method="post"><input type="hidden" id="pID" name="productID" value="' + s.id + '" /><input type="text" id="addItemWidget-amount" class="amount text" name="amount" size="2" value="' + s.amount + '" /> <span class="unit">' + s.unit + '</span> <input type="submit" class="btn" value="Læg i kurv" /></form><p id="addItemWidget-msg">'+s.msg+'</p><p id="addItemWidget-dug"></p></div><span id="addItemWidget-close">x</span></div>');
	}
	
	function prepare() {
		
		//create the markup if it doesn't exist...
		if ($('#addItemWidget').length == 0) renderMarkup();

		//BR 071214
		//check for bgIframe plugin (only used for IE6)
		if(typeof($.fn.bgIframe) == "function")
			$('#addItemWidget').bgIframe();

		//make sure the buttons are enabled!
		$("#addItemWidget-btn").attr("disabled",false).css("opacity",1)
		$("#addItemWidget-amount").attr("disabled",false);

		//add a submit event to catch the ajax post
		$('#addItemWidget-form').unbind("submit").submit(add);
		
		$('#addItemWidget-msg').hide();
		$('#addItemWidget-dug').hide();		
		$('#addItemWidget-close').css("display","none").unbind("click").bind("click",function() { hide(); });

		//stop clicks within the widget from propagating down to body.
		$('#addItemWidget').hide().bind("click", function(e) {e.stopPropagation();});
		
		$('#addItemWidget-msg').html(s.msg);
		$('#addItemWidget-unit').text(s.unit);
		$('#addItemWidget-amount').val(s.amount);
		$('#addItemWidget-id').val(s.id);
		
		$('body').unbind("click").bind("click",function(){
			hide();
			$("#addItemWidget-dug_checkbox").attr("checked","");
		});
		$(document).bind('keydown', function(e){
			var key = e.which || e.keyCode || -1;
			if (key == 27) { hide(); }
		});
		
	}
	
	//hides the widget
	function hide() {
		if(animating) return false;
		animating = true;
		$(document).unbind('keydown');
		$('body').unbind("click");
		$("#addItemWidget-close").hide();
		//FF for Mac has an issue with animation opacity, it flickers the antialias of all the text on the page.
		if (!FFMac) {
			$('#addItemWidget').animate({opacity:"hide",height: 'hide'}, 300,"linear", function(){ animating = false; });			
		} else {
			$('#addItemWidget').animate({height: 'hide'}, 200,"linear", function(){ animating = false; });
		}
	}
	
	//calculates the height and width
	function show() {
		prepare(); //prepare the widget data
		animating = true;
		//check whether to display the extra message:
		(!s.msg == '') ? $('#addItemWidget-msg').css('display','block') : $('#addItemWidget-msg').css('display','none');
		//check whether to display the extra message:
		(!s.dug == '') ? $('#addItemWidget-dug').css('display','block') : $('#addItemWidget-dug').css('display','none');
		//we need to set visibility:hidden and display:block in order to calculate the width.
		$('#addItemWidget').css({display:'block', visibility:'hidden'});		
		var offset = $(el).offset({margin:1, border:0, padding:1, scroll:1});
		offset.top += el.height() + 2; //2px extra top margin...
		offset.left -= parseInt( ($('#addItemWidget').width() - $(el).width())/2 );
		//reset the display, and prepare for animation
		$('#addItemWidget').css(offset);
		$('#addItemWidget').css({display:'none', visibility:'visible'});

		//position the widget and show it
		$('#addItemWidget').animate({ height: "show" }, 400,"backout", function() {
			animating = false;
			//after the animation is finished: focus and select amount
			$('#addItemWidget-amount').focus().select();
			//show the close button and attach click- and key handlers
			$("#addItemWidget-close").show();
		});
	}
	
	show();
	return false;
}






//Displays a hint text upon focus on an input or select element...
function prepareInputsForHints() {
	var inputs = document.getElementsByTagName("input");
	for (var i=0; i<inputs.length; i++){
		// test to see if the hint span exists first
		if (span = inputs[i].parentNode.getElementsByTagName("span")[0]) {
			if (span.className.indexOf('hint') == -1) return;
			// the span exists!  on focus, show the hint
			span.innerHTML += '<span class="hint-pointer">&nbsp;</span>';
			inputs[i].onfocus = function () {
				this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
			}
			// when the cursor moves away from the field, hide the hint
			inputs[i].onblur = function () {
				this.parentNode.getElementsByTagName("span")[0].style.display = "none";
			}
		}
	}
	// repeat the same tests as above for selects
	var selects = document.getElementsByTagName("select");
	for (var k=0; k<selects.length; k++){
		if (selects[k].parentNode.getElementsByTagName("span")[0]) {
			selects[k].onfocus = function () {
				this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
			}
			selects[k].onblur = function () {
				this.parentNode.getElementsByTagName("span")[0].style.display = "none";
			}
		}
	}
}

function hideNotice(el) {
	el = el || "addNotice";
	var obj = $('#'+el);
	if (obj.length>0) {
		setTimeout("$('#" + el + "')"+".slideUp('slow','expoout')",4000);
	}
}

$(function(){
	prepareInputsForHints();
	
	
	// scroll panel behaviour for environment image list products...
	// Firefox Mac has a bug with elements positioned over scrollbars, so ignore FFMac
	if (!FFMac && document.getElementById("environmentImage")) {
		$(window).load(function (){ //we must wait until the image is loaded...
			var $image = $("#environmentImage img:first");
			var imgHeight = $image.height() + 24 // borders+padding...I know!;
			var $products = $("#environmentProducts");
			var h = imgHeight - ($products.offset().top - $image.offset().top)
			if (h < $products.height()) {
				h = (h < 300) ? 300 : h;
				$products.addClass('scrolling').css("height", (h-4) + 'px'); // 4 = top+bottom border.					
			}
		});
	}
});



// Form serialize util functions. used instead of the buggy one in jquery < 1.2
// source: http://www.malsup.com/jquery/form/
(function($) {
	$.fn.fieldSerialize = function(successful) {
	    var a = [];
	    this.each(function() {
	        var n = this.name;
	        if (!n) return;
	        var v = $.fieldValue(this, successful);
	        if (v && v.constructor == Array) {
	            for (var i=0,max=v.length; i < max; i++)
	                a.push({name: n, value: v[i]});
	        }
	        else if (v !== null && typeof v != 'undefined')
	            a.push({name: this.name, value: v});
	    });
	    //hand off to jQuery.param for proper encoding
		return $.param(a);
	};
	$.fn.fieldValue = function(successful) {
	    for (var val=[], i=0, max=this.length; i < max; i++) {
	        var el = this[i];
	        var v = $.fieldValue(el, successful);
	        if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
	            continue;
	        v.constructor == Array ? $.merge(val, v) : val.push(v);
	    }
	    return val;
	};
	/**
	 * Returns the value of the field element.
	 */
	$.fieldValue = function(el, successful) {
	    var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
	    if (typeof successful == 'undefined') successful = true;

	    if (successful && (!n || el.disabled || t == 'reset' || t == 'button' || (t == 'checkbox' || t == 'radio') && !el.checked ||
	        (t == 'submit' || t == 'image') && el.form && el.form.clk != el || tag == 'select' && el.selectedIndex == -1)) {
	            return null;
			}

	    if (tag == 'select') {
	        var index = el.selectedIndex;
	        if (index < 0) return null;
	        var a = [], ops = el.options;
	        var one = (t == 'select-one');
	        var max = (one ? index+1 : ops.length);
	        for(var i=(one ? index : 0); i < max; i++) {
	            var op = ops[i];
	            if (op.selected) {
	                // extra pain for IE...
	                var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
	                if (one) return v;
	                a.push(v);
	            }
	        }
	        return a;
	    }
	    return el.value;
	};
	
})(jQuery);