$j(document).ready(function() { 

	$j("a.Fancy").fancybox(); 

	$j("a.GoogleMap").fancybox({
			'frameWidth':		getInnerDimensions('w') - 200, 
			'frameHeight':	getInnerDimensions('h') - 100
	});
	
	$j(".MenuBox.Hover li.HasChildren").hover(function () {
	   $j(this).addClass("Hover");
  }, function () {
    $j(this).removeClass("Hover");
  });
	
	$j("p.FileTypeIconPdf a.DownloadBoxDownloadLink").fancybox({
			'frameWidth':		getInnerDimensions('w') - 200, 
			'frameHeight':	getInnerDimensions('h') - 100,
			'hideOnOverlayClick': false,
			'hideOnContentClick': false
	});
	
	$j(".BlogEntries h3.Foldable").click(function() {
	  $j(this).next().slideToggle();
	});

	$j("div.BlogBox a.MorePaginate").live("click", function () {  
		showLoading();
		
		var link = $j(this)
		$j.get(this.href, function(data){
		  link.before(data);
			hideLoading();
		});
	  return false;  
	});
	
  $j("form.ContactForm").each(function() {
		var validator = $j(this).validate();
		var form = $j(this);
		form.submit(function () {
			if (validator.valid()) {
				showLoading();
				message = form.attr("data-msg");
				var values = "";
				
				form.children("ul").children("li").each(function(i){
					var int_id = last(this.id.split("_"));
					var value = $j(this).children("input, textarea").val();
					
					if (value == undefined) {
						value = $j("#"+this.id+" :checked").val();
					}
					
					if (value != undefined) {
						values += "fields[]["+int_id+"]="+value+"&";
					}
				});
				
				$j.post(form.attr("action"), values, function(data){
					hideLoading();
				  alert(message);
				  form.get(0).reset();
				});
			}
			return false;
		});
	});
	
});

function last(array) {
	return array[array.length-1];
}

function replaceIfExist( dom_id, content ) {
	if( $(dom_id) ) {
		$(dom_id).replace( content );
	}
}

function fadeAndRemove( selector ) {
	$$(selector).each(function(box){
		box.fade();
	});
	
	setTimeout(function() { 
		$$(selector).each(function(box){
			box.remove();
		});
	}, 1000);
}

function toggle_vat( vat ) {
	if(vat) {
		$j(".WithVatPriceVersion").show();
		$j(".WithoutVatPriceVersion").hide();
		$j(".VatToggler").replaceWith("<a href='#' onclick='toggle_vat(false); return false;' class='VatToggler'>Visa exkl. moms</a>")
	} else {
		$j(".WithVatPriceVersion").hide();
		$j(".WithoutVatPriceVersion").show();	
		$j(".VatToggler").replaceWith("<a href='#' onclick='toggle_vat(true); return false;' class='VatToggler'>Visa inkl. moms</a>")
	}
}


//formats the price and adds moms to it if moms
function getPrice( iPrice, bMoms, dec )
{
	
	var sufix = " kr"
	//Return if there is nothing to do
	if( iPrice < 0 || !isNumber( iPrice )) return "0 " + sufix;
	//if( iPrice < 100 && isInt( iPrice ) && dec === 0 ) return iPrice+sufix;
	dec = 2;
	
	//add moms and round it down to an integrer
	iPrice = bMoms ? iPrice*1.25 : iPrice;

	pres = dec ? Math.pow( 10, dec ) : 1;
	iPrice = Math.round( iPrice*pres )/pres;
	
	//transeform it to a string and split it up to an array
	if( isFloat( iPrice ) )
	{
		var sPrice = iPrice.toString(); 
		var arrPrice = sPrice.split(".");
		
		if( arrPrice[1].length < dec )
		{
			for( i=0; i<(dec-arrPrice[1].length); i++ ){ arrPrice[1] += "0"; }
		}
		arrArrPrice = arrPrice[0].split("");
		
		//place thousen-spacers every three diget
		var iTCounter = 0;
		for( i=0; i<arrArrPrice.length;i++ )
		{
			if( i % 3 == 0 && i > 2 )
			{
				arrArrPrice.splice( (-i)+(-iTCounter), 0, " " );
				iTCounter++;
			}
		}
		
		//turn the array back to a string and remove any commas, then add sufix and return the formated price!
		arrPrice[0] = arrArrPrice.join(); 
		var reSpace = /,/g;
		arrPrice[0]  = arrPrice[0] .replace( reSpace, "" ); 
		sPrice = arrPrice[0]+"."+arrPrice[1]+sufix;
	}
	else
	{
		//transeform it to a string and split it up to an array
		var sPrice = iPrice.toString(); 
		var arrPrice = sPrice.split("");
		
		//place thousen-spacers every three diget
		var iTCounter = 0;
		for( i=0; i<arrPrice.length;i++ )
		{
			if( i % 3 == 0 && i > 2 )
			{
				arrPrice.splice( (-i)+(-iTCounter), 0, " " );
				iTCounter++;
			}
		}
		
		//turn the array back to a string and remove any commas, then add sufix and return the formated price!
		sPrice = arrPrice.join(); 
		var reSpace = /,/g;
		sPrice = sPrice.replace( reSpace, "" ); 
		sPrice += ".00" + sufix;
	}
	
	return sPrice;
}

function liljengrens_valc() {
	if ( $('v_calc_rooms').value == '' || $('v_calc_m2').value == '' ) {
		$('v_calc_result').innerHTML = "Fyll i antal rum och antal kvadratmeter och försök igen.";
	} else {
		var rooms = parseFloat($('v_calc_rooms').value);
		var m2 = parseFloat($('v_calc_m2').value);
		var ventilators = 0;
		var m2_per_room = m2/rooms;
		
		if (m2_per_room > 22) {
			ventilators = m2/22;
		} else {
			ventilators = rooms;
		}
		
		//var ventilators = rooms/22;

		//if ( ventilators < rooms ) {
		//	ventilators = rooms;
		//}

		$('v_calc_result').innerHTML = "Du behöver " + Math.round(ventilators) + " st ventiler.";
	}
  return false;
}


function hide( element ) {
	if($(element)) {
		$(element).hide();
	}
}

function fade( element ) {
	if($(element)) {
		$(element).fade();
	}
}

//get the viewports w,h
function getInnerDimensions(dim) {
	var viewportwidth;
	var viewportheight;

	 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
	 if (typeof window.innerWidth != 'undefined') {
	      viewportwidth = window.innerWidth,
	      viewportheight = window.innerHeight
	 }

	 // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
	 else if (typeof document.documentElement != 'undefined'&& typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
	   viewportwidth = document.documentElement.clientWidth,
	   viewportheight = document.documentElement.clientHeight
	 }
	
	 // older versions of IE
   else {
	 	 viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
	   viewportheight = document.getElementsByTagName('body')[0].clientHeight
	 }

	//log( "w => " + viewportwidth + " h => " + viewportheight );

	if( dim == undefined ) {
		return [ viewportwidth, viewportheight ];
	} else if( dim == "w" ) {
		return viewportwidth;
	}	else if( dim == "h" ) {
		return viewportheight;
	}
}

function getScrollXY(dim) {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
	if( dim == undefined ) {
		return [ scrOfX, scrOfY ];
	} else if( dim == "x" ) {
		scrOfX;
	}	else if( dim == "y" ) {
		scrOfY;
	}
}

function reveal( element, position ) {
	showCentered(element, position);
}

function showCentered(selector, position, no_drag) {
	var d = getInnerDimensions(); 
	var s = getScrollXY();
	
	var el = $j(selector);
	
	setTimeout( function() { 
		/*alert("w =>" + $j(el[0]).width() + " h => " + $j(el[0]).height());
		
		var dims = el[0].getDimensions();
		var e_w = dims.width;
		var e_h = dims.height;*/
		e = [$j(el[0]).width(),  $j(el[0]).height()]; 
		
		if( position == 'right' ) {
			x = d[0] - 0;
			y = 25;
		} else if( position == 'left' ) {
			x = -(e[0] + 0);
			y = 25;
		} else {
			x = (d[0]/2)-(e[0]/2) + s[0]; 
			if( x < 0 ) { x = 0; }
			
			y = ((d[1]/2)-(e[1]/2) + s[1])-20;
			if( y < 46 ) { y = 46; }
		}
	
		el.css('left', x+'px');
		el.css('top', y+'px');
			
		if( position == 'right' ) {
			el.show();
			//el.animate({ left:-e[0]+'px'}).animate({position:'absolute', left: '0px !important;'});
			new Effect.Move( el[0].id, {x:-e[0], mode:'relative', afterFinish:function(e){
				el.addClass('MoveCompleted' + position);
			}} );
			
		} else if( position == 'left' ) {
			el.show();
			//el.animate({ left:e[0]+'px'}).animate({position:'absolute', left: '0px !important;'});
			new Effect.Move( el[0].id, {x:e[0], mode:'relative', afterFinish:function(e){
				el.addClass('MoveCompleted' + position);
			}} );
		} else {
			el.fadeIn();
		}
		
		if ( selector != '#page_management' ) {
			el.draggable();
		}
	}, 100);
}

//toggle blind on the first div or ul that has children
function toggleRelativeFirstContainer(e) {
	var match_found = false;
	$A(e.nextSiblings()).each(function(sibling){
		t = sibling.tagName
		if( match_found == false && sibling.childElements().length > 0 && (t=='DIV'||t=='UL'||t=='FORM') ) {
			match_found = true;
			Effect.toggle(sibling,'blind');
			return true;
		}
	});
	
	if( match_found == false ) {
		$A(e.ancestors()[0].nextSiblings()).each(function(sibling){
			t = sibling.tagName
			if( match_found == false && sibling.childElements().length > 0 && (t=='DIV'||t=='UL'||t=='FORM') ) {
				match_found = true;
				Effect.toggle(sibling,'blind');
				return true;
			}
		});
	}
	
	return false;
}

function clearContainers() {
	$$('.DropArea').each(function(container){
		container.innerHTML = "";
	});
}

function showLoading() {
	$('global_loading_container').show();
}
function hideLoading() {
	$('global_loading_container').hide();
}

function failMsg() {
	hideLoading();
	showFlashNotice( 'Ett fel har uppstått. Vi har blivit meddelande om felet och kommer åtgärda det så fort vi kan. Vi ber om ursäkt för detta.' );
}

function showFlashNotice( msg ) {
	$('flash_notice_message').innerHTML = msg;
	showCentered( 'flash_notice' );
}


//just for development...
function fillOutRegForm() {
	
	var random_value = Math.floor(Math.random()*999999); 
	
	$('user_first_name').value = "test_first_name";
	$('user_last_name').value = "test_last_name";
	$('user_company_name').value = "test_user_company_name";
	$('user_company_name').value = "test_user_company_name";
	$('user_email').value = "test_user_email_" + random_value + "@development.loc";
	$('user_password').value = "test_user_password";
	$('user_password_confirmation').value = "test_user_password";
	
	$('user_address').value = "test_user_address";
	$('user_zip').value = "test_user_zip";
	$('user_city').value = "test_user_city";
	$('user_phone').value = "0730000000";
	
}

function updateCartQuickInfo( html ) {
	if ( $('cart_quick_info') ) {
		$('cart_quick_info').replace( html );
	}
}

function toggleInnerHTML( dom_id, value_1, value_2 ) {
	if ( $(dom_id) ) {
		var element = $(dom_id)
		if ( element.innerHTML == value_1 ) {
			element.innerHTML = value_2;
		} else {
			element.innerHTML = value_1;
		}
	}
}

function hideAllMenus() {
	$$('.BoxOptionsPopup').each(function(menu){ 
		menu.hide(); 
	});
}

function checkCardNumber() {
	if( $('order_payment_method_mastercard').checked || $('order_payment_method_visa').checked) {
		
		var cardNumberRegExp = /^[0-9]{13,21}$/i;
		var cvvNumberRegExp = /^[0-9]{3}$/i;
		var cardNumber = $('order_card_number').value;
		var cvvNumber = $('order_cvv').value;
		
		if ( !cardNumberRegExp.test( cardNumber ) ) {
			showFlashNotice( 'Kortnummret verkar vara felaktigt, vänligen försök igen.' );
			return false;
		}
		
		if ( !cvvNumberRegExp.test( cvvNumber ) ) {
			showFlashNotice( 'CVVkoden verkar vara felaktig, vänligen försök igen.' );
			return false;
		}
		
		if ( !$('order_terms_of_service').checked ) {
			showFlashNotice( 'Du måste acceptera köpvillkoren innan du fortsätter.' );
			return false;
		}
		
		sum = 0;
		mul = 1;
		l = cardNumber.length;
		
		for (i = 0; i < l; i++) {
			digit = cardNumber.substring(l-i-1,l-i);
			tproduct = parseInt(digit ,10)*mul;
			
			if (tproduct >= 10) sum += (tproduct % 10) + 1;
			else sum += tproduct;
			
			if (mul == 1) mul++;
			else mul--;
		}
		if (!(sum % 10) == 0){
			showFlashNotice( 'Felaktigt kortnummer' );
			return false;
		}
	}
	
	showFlashNotice('Vänligen vänta medan din order bearbetas...');
	return true;
}

function showOverlayMask( dom_id ) {
	
	if( dom_id == undefined || dom_id == '' ) {
		mask = $('overlay_mask');
	} else {
		mask = $(dom_id);	
	}
	
	if ( mask ) {
		var body_height = $('body').getDimensions().height;
		var mask_height = body_height;
		var viewport_height = getInnerDimensions('h');
		
		if( $('cart') ) {
			var cart_height = $('cart').getDimensions().height;

			if ( body_height > cart_height ) {
				mask_height = body_height;
			} else {
				mask_height = cart_height;
			}
		}
		
		if( mask_height < viewport_height ) {
			mask_height = viewport_height;
		}
		
		mask.setStyle({height: mask_height + 'px'});
		mask.appear();
	}
}

/*
var global_editors = new Array(); // Global array of all our rich text widgets. Hidden or not.

function UShowEditors_timed()
{
	//log("Timer running...");
	for( var i = 0; i < global_editors.length; i++ )
	{
		// Todo: (if needed) Skip this one if a DOM parent is not visible.
		//log("Found a rich text widget. Showing it...");
		global_editors[i].show();
	}
}

// Call this one, it will call the other one shortly
function UShowEditors( event )
{
	setTimeout("UShowEditors_timed();",100);
	//log("Timer started.");
}
*/


/*function UShowEditor_timed( dom_id ){
	//log("Fixing "+dom_id );
	
	var ta = document.getElementById(dom_id);
	if(ta != null){
	  var editor = new YAHOO.widget.Editor(ta,{});
	  editor.render();
		//log(dom_id+" turned into a rich text editor.");
		editor.show();
	}
	else{
		//log("Unable to find dom_id");
	}
}

function UShowEditor( dom_id ){
	//log("Setting timer.")
	setTimeout("UShowEditor_timed('"+dom_id+"');",100);
}*/

function removeNewBoxes() {
	$$('.NewBox').each(function(b){ 
		b.fade();
		
		b.remove.delay(1); 
	});
}

function replceLoginFormWithIEWarning() {
	if( !isAdminCompatible() ) {
		$('login_form_container').innerHTML = '<div class=\"UpgradeBrowserNow\" onclick=\"$(\'login_form_container\').fade();\"><h3>Vänligen ladda ner Firefox 3 för att logga in</h3><p>För att logga in krävs webbläsaren Firefox 3 tryck <a href=\"http://www.getfirefox.com\" onclick=\"window.open(\'http://www.getfirefox.com\', \'newWindow\'); return false;\" rel=\"external\" title=\"Ladda ner Firefox 3\">här</a> för att ladda ner det.</p></div>' 
	}
}

function removeLoginForm() {
	if( $('login_form_container') ) {
		$('login_form_container').remove();
	}
}

function isAdminCompatible() {
	//TODO: fix so that it's only Firefox 3 that is accepted here
	if( Prototype.Browser.Gecko || Prototype.Browser.WebKit ) {
		return true;
	} else {
		return false;
	}
}

function insertOrUpdate( location, content ) {
	if( $(location) ) {
		Element.replace(location, content );
	} else {
		Element.insert( 'body', content );
	}
}

function makeFullscreen( element ) {
	dims = getInnerDimensions();
	w = dims[0] - 100;
	h = dims[1] - 100;
	
	$(element).setStyle({
	  width: w + 'px',
	  height: h + 'px'
	});
	$('flash_notice').setStyle({
	  left: '10px',
	  top: '35px',
		width: w + 'px',
	  height: h + 'px',
		opacity: 100
	});
	
	showOverlayMask();
}

function select_option_redirect(targ, selObj) {
	if( selObj.options[selObj.selectedIndex].value == "Select language" || selObj.options[selObj.selectedIndex].value == "" ) {
		selObj.selectedIndex=0;
		return;
	}
	
	eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
	selObj.selectedIndex=0;
}

String.prototype.trim = function( replacer ) {
	if( replacer = undefined ) replacer = '';
	
	a = this.replace(/^\s+/, replacer);
	return a.replace(/\s+$/, replacer);
};

String.prototype.highlight = function( keywords ) {
	string = ''
	this.split(' ').each(function(word) {
		keywords.split(' ').each(function(keyword) {
			if( word.trim() == keyword.trim()) {
				string += '<strong>' + word + '</strong>';
			} else {
				string += word;
			}
		});
	});
	return string;
};

String.prototype.truncate = function( length ) {
	if( length == undefined ) {
		length = 150;
	}
	truncated = this.slice(0,length)
	if( truncated.length < this.length ) {
		return truncated + '...';
	} else {
		return truncated;
	}
};

String.prototype.linebreak = function( break_at ) {
	if( this.length <= break_at ) {
		return this;
	} else {
		return this.slice(0,break_at) + '<br />' + this.slice(break_at,this.length)
	}
};

function pageChangeWithFadeEffect( url ) {
	Effect.Fade('main_container');
	window.setTimeout(function() {
	 window.location = url }, 1000);
	return false;
}

function inspect(obj, maxLevels, level)
{
  var str = '', type, msg;

    // Start Input Validations
    // Don't touch, we start iterating at level zero
    if(level == null)  level = 0;

    // At least you want to show the first level
    if(maxLevels == null) maxLevels = 1;
    if(maxLevels < 1)     
        return '<font color="red">Error: Levels number must be > 0</font>';

    // We start with a non null object
    if(obj == null)
    return '<font color="red">Error: Object <b>NULL</b></font>';
    // End Input Validations

    // Each Iteration must be indented
    str += '<ul>';

    // Start iterations for all objects in obj
		str = ''
		for(property in obj) {
			try {
				type = typeof(obj[property]);
				str += " " + property + ": '" + obj[property] + "',\n"
				
				if((type == 'object') && (obj[property] != null) && (level+1 < maxLevels))
        str += inspect(obj[property], maxLevels, level+1);
			} catch(err) {
				str += " 'unknown', "
			}
		}

/*
    for(property in obj)
    {
      try
      {
          // Show "property" and "type property"
          type =  typeof(obj[property]);
          str += '<li>(' + type + ') ' + property + 
                 ( (obj[property]==null)?(': <b>null</b>'):('')) + '</li>';

          // We keep iterating if this property is an Object, non null
          // and we are inside the required number of levels
          if((type == 'object') && (obj[property] != null) && (level+1 < maxLevels))
          str += inspect(obj[property], maxLevels, level+1);
      }
      catch(err)
      {
        // Is there some properties in obj we can't access? Print it red.
        if(typeof(err) == 'string') msg = err;
        else if(err.message)        msg = err.message;
        else if(err.description)    msg = err.description;
        else                        msg = 'Unknown';

        str += '<li><font color="red">(Error) ' + property + ': ' + msg +'</font></li>';
      }
    }

      // Close indent
      str += '</ul>';
*/
    return str;
}

function isArray(a){ return isObject(a) && a.constructor == Array;}
function isBoolean(a){ return typeof a == 'boolean';}
function isFunction(a){ return typeof a == 'function';}
function isNull(a){ return typeof a == 'object' && !a;}
function isNumber(a){ return typeof a == 'number' && isFinite(a);}
function isInt(a){ return ((a % 1) == 0) ? true : false;}
function isFloat(a){ return ((a % 1) == 0 && isNumber(a) ) ? false : true;}
function isObject(a){ return (a && typeof a == 'object') || isFunction(a);}
function isString(a){ return typeof a == 'string'; }
function isUndefined(a){ return typeof a == 'undefined'; } 
function isEmpty(o) 
{
	var i, v;
	if (isObject(o))
	{
		for (i in o)
		{
			v = o[i];
			if (isUndefined(v) && isFunction(v)) return false;
		}
	}
    return true;
}


jQuery.fn.fadeToggle = function(speed, easing, callback) {
    return this.animate({opacity: 'toggle'}, speed, easing, callback);
};