﻿/*
 * jQuery ifixpng plugin
 * (previously known as pngfix)
 * Version 2.1  (23/04/2008)
 * @requires jQuery v1.1.3 or above
 *
 * Examples at: http://jquery.khurshid.com
 * Copyright (c) 2007 Kush M.
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
(function($) {
	$.ifixpng = function(customPixel) {
		$.ifixpng.pixel = customPixel;
	};
	
	$.ifixpng.getPixel = function() {
		return $.ifixpng.pixel || 'images/default/778_fall_pixel.gif';
	};
	
	var hack = {
		ltie7  : $.browser.msie && $.browser.version < 7,
		filter : function(src) {
			return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=crop,src='"+src+"')";
		}
	};
	 
	$.fn.ifixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			// in case rewriting urls
			var base = $('base').attr('href');
			if (base) {
				// remove anything after the last '/'
				base = base.replace(/\/[^\/]+$/,'/');
			}
			if ($$.is('img') || $$.is('input')) { // hack image tags present in dom
				if ($$.attr('src')) {
					if ($$.attr('src').match(/.*\.png([?].*)?$/i)) { // make sure it is png image
						// use source tag value if set 
						var source = (base && $$.attr('src').search(/^(\/|http:)/i)) ? base + $$.attr('src') : $$.attr('src');
						// apply filter
						$$.css({filter:hack.filter(source), width:$$.width(), height:$$.height()})
						  .attr({src:$.ifixpng.getPixel()})
						  .positionFix();
					}
				}
			} else { // hack png css properties present inside css
				var image = $$.css('backgroundImage');
				if (image.match(/^url\(["']?(.*\.png([?].*)?)["']?\)$/i)) {
					image = RegExp.$1;
					image = (base && image.substring(0,1)!='/') ? base + image : image;
					$$.css({backgroundImage:'none', filter:hack.filter(image)})
					  .children().children().positionFix();
				}
			}
			return this;
		});
	} : function() { return this; };
	
	$.fn.iunfixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			var src = $$.css('filter');
			if (src.match(/src=["']?(.*\.png([?].*)?)["']?/i)) { // get img source from filter
				src = RegExp.$1;
				if ($$.is('img') || $$.is('input')) {
					$$.attr({src:src}).css({filter:''});
				} else {
					$$.css({filter:'', background:'url('+src+')'});
				}
			}
		});
	} : function() { return this; };
 
	$.fn.positionFix = function() {
		return this.each(function() {
			var $$ = $(this);
			var position = $$.css('position');
			if (position != 'absolute' && position != 'relative') {
				$$.css({position:'relative'});
			}
		});
	};
})(jQuery);

jQuery.fn.setFirstTextNode= function(txt){return this.each(function(){var $=jQuery,c=$(this).contents().filter(function(){ return this.nodeType==3&&$.trim(this.nodeValue).length>0;})[0];if(c)c.nodeValue=txt;})};

var GUI = (function() {
	function initGUI() {		
		
		ApplaySpotBoxStructure();
		InitializeSections();
		
		if ( $.browser.msie && typeof document.documentElement.style.maxHeight == 'undefined' ) {
			$('input[type="text"]').addClass('ietextfield');
			$('textarea').addClass('ietextarea');
		}
	}
	
	function ApplaySpotBoxStructure() {
		
		$('.spotBox:not(.nogui)').each(function() {
			var item = $(this);
       
			item.wrapInner(
				$('<div>').addClass('bw').append(
					$('<div>').addClass('bw2').append(
						$('<div>').addClass('content selfClear')
					)
				)
			);

			var top = $('<div>').addClass('bt'); if (!item.is('.plain')) top.append('<div>');
			var bottom = $('<div>').addClass('bb'); if (!item.is('.plain')) bottom.append('<div>');
			item.prepend(top);
			item.append(bottom);
			
			if ( item.is('.jqmWindow') ) {
				item.append( $('<div></div>').addClass('modalClose') );
			}			
		});
	}
	
	function InitializeSections() {
		
		var page = $('.action').attr('id');
		if ( page ) {
			if ( sections[page] ) sections[page].apply(this, []);
		}
		$('.iconprint').click( function() { window.print(); } );
	}
	
	function jqmWindowOpen( hash ) {
		var marginLeft = -parseInt( hash.w.width()/2 );
		hash.w.css("margin-left", marginLeft + 'px' ).show();
	}
	
	function jqmProductInfoOpen( hash ) {
		
		
		
		$( '.productTitle', hash.w).html( $('.productTitle', hash.t).text() + "&nbsp;" );
		$( '.productPrize', hash.w).html( $('.productPrize', hash.t).text() );
		$( '.productDesctiption', hash.w).text( $('.productDesc', hash.t).text() );
		
		/* TH KOD
		    satt href på länk
		*/
		$('.navBtnAddToCart',hash.w).attr('href', '?additem=' + $('.productId', hash.t).text());
		
		
		
		/* TH Ändring
			Ändrade så att inte hela sidans Cufon laddades om.		
		*/
		
		/* Bortaget av TH
		var img = $('img', hash.w );
		var srcimg = $('img', hash.t);
		var src = srcimg.attr('src').split('.');
		
		img.attr('src', src[0] + '_big.' + src[1] );
		*/
		
		/* TH Ändring
			Ändrade så att bilden laddades från ett dolt fält inte som i koden ovan.	
		*/
		var srcimg = $('.imageBig', hash.t).text();
		$('img', hash.w ).attr('src',srcimg);
		/* SLUT TH ändring */
		
		/* TH Ändring 
		 Ändrade så att inte hela sidas Cufon laddades om.
		*/
		try{
		    
		    //Cufon.refresh();
		    
		    Cufon.refresh('.productPrize', { fontFamily: 'foundryOSF' }); 
		    Cufon.replace('.productTitle', { fontFamily: 'foundry' });
		}catch(e)
		{
		    //alert(e);
		}
		/* SLUT TH ändring */
		
		var clickIndex = $(hash.t).parent().find('a').index( hash.t )+1;
		var colIndex = clickIndex % 3;
		if ( colIndex == 0 ) colIndex = 3;
		switch ( colIndex ) {
			case 1:
				hash.w.css('left', '10px');
				break;
			case 2:
				hash.w.css('left', '195px');
				break;
			case 3:
				hash.w.css('left', '390px');
				break;
		}
		
		/* TH Ändring 
		 	Ändrade så att om webbläsaren är IE6 så öppnas inte popupen och varan läggs till direkt.
		*/
		if ( $.browser.msie && typeof document.documentElement.style.maxHeight == 'undefined' ) {
			$('.navBtnAddToCart').trigger('click');
			return;	
		};
		/* SLUT TH ändring */
		
		hash.w.show();
	}
	
	var sections = {
		"startpage" : function() {
			$('.jqmWindow').jqm({onShow: jqmWindowOpen, modal:false, closeClass: 'modalClose'});
			$('.overlay').click( function() {
				var link = $(this);
				var rel = link.attr('rel');
				if ( rel ) {
					$('#'+rel).jqmShow();
				}
			});
			
			//
			$('.navBtnGoToCashier').click(function(){
			    if($('#prodListContent .prodTitle').length == 0)
			    {
			          return false;
			    }
			});
			
			$('#overlay_productinfo').jqm({onShow: jqmProductInfoOpen});
			$('.productItem').click( function() {
			   	try{
			   	    $('#overlay_productinfo').jqmShow(this);
			   	}catch(e){
			   	      // alert(e);
			   	}
				return false;
			});			
		},
		"checkout" : function() {
			//$('select').jcombox({relativeTo: '#container', theme: 'skdropd'});
			
			var prevSel = null;
			var formValueEl = $('#paymentMethod .payment_method');
			
			/* START TH KOD */
			    if($(formValueEl).val() != "")
			    {
			        val = $(formValueEl).val()
			        switch(val)
			        {
			            case "CARD" :
			                $('.pmethodCreditcard').addClass('pmethodCreditcardActive');
			                prevSel = $('.pmethodCreditcard');
			            break;	
			            case "FSB/IB" :
			                $('.pmethodSwebank').addClass('pmethodSwebankActive');
			                prevSel = $('.pmethodSwebank');
			            break;	
			            case "SHB/IB" :
			                $('.pmethodHBank').addClass('pmethodHBankActive');
			                 prevSel = $('.pmethodHBank');
			            break;	
			            case "NB/IB" :
			                $('.pmethodNordea').addClass('pmethodNordeaActive');
			                 prevSel = $('.pmethodNordea');
			            break;	
			            case "SEB/IB" :
			                $('.pmethodSeb').addClass('pmethodSebActive');
			                prevSel = $('.pmethodSeb');
			            break;  			        		    
    			    
			        }			    
			    }
			/* SLUT TH KOD */
			
			$('#paymentMethod a').click( function() {
				var item = $(this);
				var currentClass = item.attr('class'), activeClass = '';
				
				if ( prevSel ) {
					prevSel.attr('class', prevSel.attr('class').split(' ')[0]);
					if ( $.browser.msie && typeof document.documentElement.style.maxHeight == 'undefined' ) { prevSel.height('21px'); }
				}
				
				if ( currentClass.indexOf(' ') > -1 ) {
					activeClass = currentClass.split(' ')[0] + 'Active';
				} else {
					formValueEl.val(currentClass);
					activeClass = currentClass + 'Active';
				}
				prevSel = item;
				item.toggleClass(activeClass);
			});
			
			//$('#personalInformation input[type="text"]').inputLabel();
			
			/*'
			    $('#personalInformation input[type="text"]').each(function(){
			        var lbl = $(this).prev();
			        if($(this).val() == "")
			            $(this).val($(lbl).text());
    			    
			        $(this).focus(function () {
			            if($(this).val() == $(lbl).text())
			               $(this).val("");
    			         
			        }).blur(function(){
			             if($(this).val() == "")
			               $(this).val($(lbl).text());
			        });

			        $(lbl).hide();
			    });
			*/
			
			$('.subSection').hover(
				function() {
					$('.helptext').hide();
					var cont = $(this);
					var help = $('.helptext', this);
					if ( $.browser.opera ) help.css('left', '-99999px').show();
					var cord = parseInt(cont.height()/2)-parseInt(help.height()/2);
					if ( $.browser.opera ) help.css('left', 'auto').hide();
					help.css('top', cord+'px').show();
				},
				function() {
					$('.helptext', this).hide();
				}
			);
			$('.helptext').ifixpng();
			
		},
		"reciept": function() {
			//$('#electronicGiftCertForm input[type="text"],#electronicGiftCertForm textarea').inputLabel();
		},
		"tipfriend": function() {
			var rowCount = 5;
			//$('#tipfriendYourInfo input[type="text"],#tipfriendInfo input[type="text"]').inputLabel();
			$('#btnAddFriend').click( function() {
				var newRowIndex = rowCount++;
				var row = $('#tipfriendInfo .frmRow:last');
				var newRow = row.clone();
				$('.leftCol label', newRow).attr('for', 'txtName' + newRowIndex );
				$('.leftCol input', newRow).attr('name', 'txtName' + newRowIndex );
				$('.leftCol input', newRow).attr('id', 'txtName' + newRowIndex );
				
				$('.rightCol label', newRow).attr('for', 'txtAddress' + newRowIndex );
				$('.rightCol input', newRow).attr('name', 'txtAddress' + newRowIndex );
				$('.rightCol input', newRow).attr('id', 'txtAddress' + newRowIndex );
				
				newRow.insertBefore( this );
				//$('input[type="text"]', newRow).inputLabel();
				return false;
			});
		}
	}
	
	return {
		init: initGUI
	}
})();

$(document).ready(function() {
	GUI.init();
});