/**
 * @theme: esafe
 * @file: core.js
 * @author: designovermatter
 */

/*

Basic page functions.

*/
function navigate(url) {
	window.location = url;
} // navigate()

/*

Ictinus shorthand.

*/
function corners() {
	for(var i = 0; i < arguments.length; i++) {
		jQuery("#" + arguments[i]).load(function() {
			//var arg = jQuery(this).attr("id");
			ictinus.cutCorners(this);
		});
	}
}

/**
 * Format price
 */
function price_format( number, decimal ) {
	if( undefined == decimal )
		decimal = 0;
	var digits = number.toString();
	var sign = digits.indexOf( '-' ) == 0 ? '-' : '';
	number = Math.abs( number );
	if( 0 == number )
		return sign + '0.00';
	var digits = number.toString();
	if( 0 < digits.indexOf( '.' ) )
		digits = digits.substr( 0, digits.indexOf( '.' ) );
	var decimals = ( number * 100 ).toString().substr( digits.length, digits.length + 2 );
	var integer = '';
	var count = 0;
	for( var i = digits.length - 1; i >= 0; i-- ) {
		integer = digits[ i ] + ( count > 0 && count % 3 == 0  ? ' ' : '' ) + integer;
		count++;
	}
	var formatted = sign + integer;
	if( 0 < decimal )
		formatted = formatted + '.' + decimals;
	return formatted;
}

/*

Hashpipe.

*/
var hashpipe = {
	set:function(hash) {
		if(window.location.hash != hash) {
			window.location.hash = hash;
			return false;
		}
	}, // set()
	get:function() {
		return window.location.hash.substr(1);
	} // get()
} // hashpipe()

/*

User functions.

*/
var user = {
	promptLogin:function() {
		jQuery("#overlay")
			.width(document.body.clientWidth)
			.height(document.body.clientHeight);
		jQuery("#dialog").html(
			'<div id="login-promt">' +
			'    <div class="top"></div>' +
			'    <form id="promt-login-form" action="#" method="post">' +
			'        <h1>Logga in</h1>' +
			'        <div class="field">' +
			'            <label for="prompt-username">Anv&auml;ndarnamn</label>' +
			'            <input type="text" id="prompt-username" name="username" value="" />' +
			'        </div>' +
			'        <div class="field">' +
			'            <label for="prompt-password">L&ouml;senord</label>' +
			'            <input type="password" id="prompt-password" name="password" value="" />' +
			'        </div>' +
			'        <div class="buttons">' +
			'            <a class="button" href="#"><span>Logga in</span></a>' +
			'        </div>' +
			'    </form>' +
			'    <div class="bottom"></div>' +
			'</div>'
		);
		$t(jQuery("#login-button")).tween({right:-(screen.width / 6 + jQuery("#login-button").width() * 2)});
		jQuery("#overlay").fadeTo("fast", 0.7);
		jQuery("#dialog").css("top", parseInt(((screen.height - jQuery("#dialog").height()) / 2))).css("left", screen.width - jQuery("#dialog").height() * 2);
		jQuery("#dialog").fadeIn("fast");
		$t(jQuery("#dialog")).tween({left:parseInt(((screen.width - jQuery("#dialog").width()) / 2))});
		return false;
	} // promtlogin()
}; // user

/*
Simple scroller.
*/
var scroller = {
	defaults:{
		duration:5000,
		width:817
	}, // defaults
	options:{}, // options
	init:function(options) {
		scroller.options = jQuery.extend({}, scroller.defaults, options);
		scroller.campaigns = jQuery(".roller .banner").size();
		var ff_fix = (jQuery.browser.mozilla ? -28 : 0);
		scroller.arrow_left = {
			start_pos:jQuery("#screen .left").css("left").replace("px","") * 1 + ff_fix,
			offset_pos:jQuery("#screen .left").css("left").replace("px","") - 8 + ff_fix
		};
		scroller.arrow_right = {
			start_pos:jQuery("#screen .right").css("right").replace("px","") * 1 + ff_fix,
			offset_pos:jQuery("#screen .right").css("right").replace("px","") * 1 - 8 + ff_fix
		};
		scroller.arrows();
		scroller.leaf(scroller.options.duration);
	}, // initialize()
	arrows_anim:null,
	arrow_left:{},
	arrow_right:{},
	arrows:function() {
		jQuery("#screen")
			.mouseover(function() {
				if(scroller.arrows_anim !== null) {
					scroller.arrows_anim.stop();
				}
				scroller.arrows_anim = $t(jQuery(this).find(".arrow")).tween({opacity:1});
				
				if(!scroller.arrows_busy) {
					scroller.arrows_busy = true;
					jQuery(this).find(".arrow").fadeIn("fast", function() {
						scroller.arrows_busy = false;
					});
				}
				else {
					jQuery(this).find(".arrow").show();
					scroller.arrows_busy = false;
				}
				//auto scroll
				if(scroller.leaf_anim != null) {
					clearTimeout(scroller.leaf_anim);
				}
			})
			.mouseout(function() {
				scroller.arrows_anim = $t(jQuery(this).find(".arrow")).tween({opacity:0});
				//auto scroll
				scroller.leaf(scroller.options.duration);
			});
			jQuery("#screen").find(".left").click(function() {
				scroller.previous();
			})
			jQuery("#screen").find(".right").click(function() {
				scroller.next();
			});
	}, // arrows()
	campaigns:0,
	current:0,
	previous:function() {
		//animation
		jTweener.addTween(jQuery("#screen .left"), {
			left:scroller.arrow_left.offset_pos,
			time:0.1,
			onComplete:function() {
				jTweener.addTween(jQuery("#screen .left"), {
					left:scroller.arrow_left.start_pos,
					time:0.2
				});
			}
		});
		//scroll
		scroller.goto(scroller.current - 1);
	}, // previous()
	next:function() {
		//animation
		jTweener.addTween(jQuery("#screen .right"), {
			right:scroller.arrow_right.offset_pos,
			time:0.1,
			onComplete:function() {
				jTweener.addTween(jQuery("#screen .right"), {
					right:scroller.arrow_right.start_pos,
					time:0.2
				});
			}
		});
		//scroll
		scroller.goto(scroller.current + 1);
	}, // next()
	goto:function(c) {
		if(scroller.current != c) {
			if(c > scroller.campaigns - 1) {
				c = 0;
			}
			else if(c < 0) {
				c = scroller.campaigns - 1;
			}
			var new_x = scroller.options.width * c;
			jTweener.addTween(jQuery("#screen .roller"), {
				left:new_x * -1,
				time:1
			});
			scroller.current = c;
		}
	}, // goto()
	leaf_anim:null,
	leaf:function(duration) {
		if(scroller.leaf_anim != null) {
			clearTimeout(scroller.leaf_anim);
		}
		scroller.leaf_anim = setTimeout("scroller.next(); scroller.leaf(" + duration + ");", duration);
	} // leaf()
}; // scroller

/*
Simple guide script.
*/
var guide = {
	defaults:{},
	options:{},
	contents:[],
	initialize:function(options, contents) {
		guide.options = jQuery.extend({}, guide.defaults, options);
		guide.contents = contents;
		//setup events
		jQuery(guide.options.holder + " .navigation a").live("click", function() {
			var hash = jQuery(this).attr("href").substr(1);
			guide.display(hash);
			return false;
		});
		jQuery(guide.options.holder + " input[name=answer]").live("change", function() {
			var hash = jQuery(this).val();
			hashpipe.set(hash);
			guide.display(hash);
		});
		//run hashed
		var hash = hashpipe.get();
		if(hash !== "") {
			//fix (to not redirect when loaded)
			var numbers = hash.split(",");
			numbers.pop();
			hash = numbers.join(",");
			guide.display(hash);
		}
		else {
			guide.display("0");
		}
	}, // initialize()
	fx:function(hash) {
		jTweener.addTween(jQuery(guide.options.holder + " .holder"), {
			opacity:0,
			time:0.1,
			onComplete:function() {
				guide.display(hash);
				jTweener.addTween(jQuery(guide.options.holder + " .holder"), {
					opacity:0,
					time:0.2
				});
			}
		});
	}, // fx()
	display:function(hash) {
		var letters = "abcdefghijklmnopqrstuvxyz";
		var numbers = hash.split(",")
		var current = guide.contents;
		var previous = [];
		var hash = [];
		//navigation
		var navigation = [];
		for(var i = 0; i < numbers.length; i++) {
			previous = current;
			//check if url property exists
			if(current[numbers[i]].url !== undefined) {
				navigate(current[numbers[i]].url);
				//alert("Gone to: " + current[numbers[i]].url);
				return false;
			}
			hash.push(numbers[i]);
			navigation.push('<a href="#' + hash.join(",") + '">' + current[numbers[i]].label + '</a>');
			current = current[numbers[i]].answers;
		}
		//question
		var question = previous[numbers[numbers.length-1]].question;
		//answers
		var answers = [];
		for(var i = 0; i < previous[numbers[numbers.length-1]].answers.length; i++) {
			answers.push('<td><input id="answer-' + letters[i] + '" type="radio" name="answer" value="' + hash.join(",") + ',' + i + '" /></td><td><label for="answer-' + letters[i] + '">' + previous[numbers[numbers.length-1]].answers[i].answer + '</label></td>');
		}
		var holder = jQuery(guide.options.holder);
		holder.html(
			'<div class="holder">' +
			'    <div class="navigation">' + navigation.join(" &rarr; ") + '</div>' +
			'    <div class="question">' +
			'        <h2>' + question + '</h2>' +
			'        <table class="answers"><tr>' + answers.join("</tr><tr>") + '</tr></table>' +
			'    </div>' +
			'</div>');
	} // display()
};

/**
 * Preload images and run callback
 */
jQuery.fn.preload = function( callback ) {
	checklist = this.toArray();
	this.each( function() {
		if( in_array( this, widnow.preloaded ) ) {
			callback();
			return;
		}
		jQuery( '<img />' ).attr( {
			src:this
		} ).load( function() {
			checklist.splice( checklist.indexOf( jQuery( this ).attr( "href" ) ), 1 );
			window.preloaded.push( jQuery( this ).attr( "href" ) );
			if( checklist.length == 0 )
				callback();
		} );
	} );
};
function in_array( needle, haystack ) {
	var found = false;
	jQuery.each( haystack, function( i, stack ) {
		if( needle == stack )
			found = true;
	} );
	return found;
}

/**
 * Alert
 */
function update_alert_select( alert_fee, vat_rate ) {
	if( 1 == jQuery( "select[name=alert]" ).val() ) {
		jQuery( ".column-price.alert" ).html( price_format( alert_fee, 2 ) + ' kr' );
		jQuery( "input[name=alert_price]" ).val( alert_fee );
	}
	else {
		jQuery( ".column-price.alert" ).html( price_format( 0, 2 ) + ' kr' );
		jQuery( "input[name=alert_price]" ).val( 0 );
	}
	var sum = 0;
	jQuery( "input[name=price[]]" ).each( function() {
		sum = sum + jQuery( this ).val() * 1;
	} );
	sum = sum + jQuery( "input[name=alert_price]" ).val() * 1;
	jQuery( ".column-price.total" ).html( price_format( sum * vat_rate, 2 ) + ' kr' );
	jQuery( "input[name=sum]" ).val( sum );
	jQuery( ".column-price.vat" ).html( price_format( sum * vat_rate - sum, 2 ) + ' kr' );
}

/**
 * Klarna API integration
 */
function klarna_get_addresses( ssn, that, alert_fee, vat_rate ) {
	jQuery.ajax( {
		url:"/wp-content/plugins/catalogue/ajax.php",
		data:{ method:"get_addresses", ssn:ssn },
		success:function( result ) {
			if( result.error )
				if( "undefined" == typeof dialogue )
					alert( result.errmsg );
				else
					dialogue.prompt( that, '<h1>Fel</h1><p>' + result.errmsg + '</p>' );
			else {
				jQuery( "#company_name" ).val( result.data.company_name );
				if( '' != result.data.surname && jQuery( "#surname" ).val() != result.data.surname )
					jQuery( "#surname" ).val( result.data.surname );
				if( '' != result.data.lastname && jQuery( "#lastname" ).val() != result.data.lastname )
					jQuery( "#lastname" ).val( result.data.lastname );
				jQuery( "#street" ).val( result.data.street );
				jQuery( "#postcode" ).val( result.data.postcode );
				jQuery( "#city" ).val( result.data.city );
				if( jQuery( "#ship_to_same_address:checked" ).length ) {
					jQuery( "#shipping_street" ).val( result.data.street );
					jQuery( "#shipping_postcode" ).val( result.data.postcode );
					jQuery( "#shipping_city" ).val( result.data.city );
				}
				// has klarna account
				if( "true" == result.data.has_account )
					jQuery( "input[name=payment_method]" ).each( function() {
						if( 'klarna_account' == jQuery( this ).val() )
							jQuery( this ).attr( { checked:true } );
						else
							jQuery( this ).removeAttr( "checked" );
					} );
				// disable fields
				var klarna_payments = [ 'klarna_invoice', 'klarna_partpayment', 'klarna_account' ];
				//alert( klarna_payments[0] );
				if( in_array( jQuery( "input[name=payment_method]" ).val(), klarna_payments ) ) {
					if( '' !== result.data.company_name ) {
						jQuery( "#company_name" ).attr( { readonly:true } );
						jQuery( "#surname" ).removeAttr( "readonly" );
						jQuery( "#lastname" ).removeAttr( "readonly" );
					}
					else {
						jQuery( "#company_name" ).removeAttr( "readonly" );
						jQuery( "#surname" ).attr( { readonly:true } );
						jQuery( "#lastname" ).attr( { readonly:true } );
					}
					jQuery( "#street" ).attr( { readonly:true } );
					jQuery( "#postcode" ).attr( { readonly:true } );
					jQuery( "#city" ).attr( { readonly:true } );
				}
				// is person
				if( '' == result.data.company_name ) {
					jQuery( "select[name=alert]" ).val( 1 ).attr( { disabled:true } );
					update_alert_select( alert_fee, vat_rate );
				}
				else
					jQuery( "select[name=alert]" ).removeAttr( "disabled" );
			}
		},
		dataType:"json"
	} );
}

/**
 * Dialogue
 */
var dialogue = {
	defaults:{
		container:"#dialogue"
	},
	state:'closed',
	obj:null,
	content_type:'text',
	init:function( options ) {
		dialogue.options = jQuery.extend( {}, dialogue.defaults, options );
		dialogue.obj = null;
		dialogue.content_type = 'text';
		if( !jQuery( dialogue.options.container ).length )
			jQuery( "#layout" ).append( jQuery( "<div />" ).attr( {
					id:dialogue.options.container.substr( 1 )
				} ).append( jQuery( "<div />" ).addClass( ".content" ) ) );
		jQuery( dialogue.options.container + " .content" ).html( '' );
		jQuery( dialogue.options.container ).css( {
			opacity:100,
			width:"auto",
			height:"auto"
		} );
		jQuery( dialogue.options.container + " .cross" ).live( "click", function() {
			dialogue.close();
			return false;
		} );
	},
	prompt:function( obj, content, content_type ) {
		if( 'opened' == dialogue.state )
			return false;
		dialogue.obj = obj;
		dialogue.content_type = content_type;
		jQuery( dialogue.options.container + " .content" ).append( content );
		dialogue.show();
	},
	show:function() {
		dialogue.state = 'opened';
		var obj_width = jQuery( dialogue.obj ).width();
		var obj_height = jQuery( dialogue.obj ).height();
		var position = jQuery( dialogue.obj ).position();
		var scrolled = jQuery( window ).scrollTop();
		var total_width = jQuery( window ).width();
		var total_height = jQuery( window ).height();
		if( 'image' == dialogue.content_type && jQuery.browser.msie ) {
			jQuery( dialogue.options.container ).css( {
				left:Math.round( total_width / 2 - width / 2 ),
				top:Math.round( total_height / 2 - height / 2 ) + scrolled,
			} ).show();
			return false;
		}
		if( 'image' == dialogue.content_type ) {
			var width = jQuery( dialogue.options.container + " img" ).attr( "width" );
			var height = jQuery( dialogue.options.container + " img").attr( "height" );
		}
		else {
			var width = jQuery( dialogue.options.container ).width();
			var height = jQuery( dialogue.options.container ).height();
		}
		jQuery( dialogue.options.container ).css( {
			left:position.left,
			top:position.top
		} );
		if( 'image' == dialogue.content_type ) {
			jQuery( dialogue.options.container + " img" ).css( {
				width:obj_width,
				height:obj_height
			} );
			jQuery( dialogue.options.container ).show();
			jTweener.addTween( jQuery( dialogue.options.container + " img" ), {
				width:width,
				height:height,
				time:0.5
			} );
			jTweener.addTween( jQuery( dialogue.options.container ), {
				left:Math.round( total_width / 2 - width / 2 ),
				top:Math.round( total_height / 2 - height / 2 ) + scrolled,
				time:0.5,
				onComplete:function() {
					dialogue.add_close_button();
				}
			} );
		}
		else {
			jQuery( dialogue.options.container ).css( {
				width:obj_width,
				height:obj_height
			} ).show();
			jQuery( dialogue.options.container + " .content" ).css( { opacity:0 } );
			jTweener.addTween( jQuery( dialogue.options.container ), {
				left:Math.round( total_width / 2 - width / 2 ),
				top:Math.round( total_height / 2 - height / 2 ) + scrolled,
				width:width,
				height:height,
				time:0.5,
				onComplete:function() {
					jTweener.addTween( jQuery( dialogue.options.container + " .content" ), { opacity:100, time:0.5 } );
					dialogue.add_close_button();
				}
			} );
		}
	},
	add_close_button:function() {
		jQuery( dialogue.options.container + " .content" ).append( '<a href="#" class="mini-button cross" style="display:none"><span>Stäng</span></a>' ).find( ".cross" ).fadeIn();
	},
	close:function(  ) {
		dialogue.state = 'closed';
		jTweener.addTween( jQuery( dialogue.options.container ), {
			opacity:0,
			time:0.5,
			onComplete:function() {
				dialogue.init( dialogue.options );
			}
		} );
		/*
		var obj_width = jQuery( dialogue.obj ).width();
		var obj_height = jQuery( dialogue.obj ).height();
		var position = jQuery( dialogue.obj ).position();
		var scrolled = jQuery( window ).scrollTop();
		if( 'image' == dialogue.content_type ) {
			jTweener.addTween( jQuery( dialogue.options.container + " img" ), {
				width:obj_width,
				height:obj_height,
				time:0.5
			} );
			jTweener.addTween( jQuery( dialogue.options.container ), {
				left:position.left,
				top:position.right,
				time:0.5,
				onComplete:function() {
					jQuery( dialogue.options.container ).hide();
					dialogue.init( dialogue.options );
				}
			} );
		}
		else {
			jTweener.addTween( jQuery( dialogue.options.container ), {
				left:position.left,
				top:position.top,
				width:obj_width,
				height:obj_height,
				time:0.5,
				onComplete:function() {
					jQuery( dialogue.options.container ).fadeOut();
					dialogue.init( dialogue.options );
				}
			} );
		}
		*/
	}
};

// onload
jQuery( function( $ ) {
	scroller.init();
	dialogue.init();
	jQuery( "#form_price_settings input[type=radio]" ).click( function() {
		jQuery( this ).parent().parent().submit();
	} );
	// images
	var image_cache = [];
	$( ".image-link" ).each( function() {
		var imgsrc = $( this ).attr( "href" );
		jQuery( '<img />' ).attr( {
			src:imgsrc
		} ).load( function() {
			if( this.complete )
				image_cache.push( imgsrc );
		} );
	} ).click( function() {
		var that = this;
		// this script is buggy in IE, so just skip it and open image in browser.
		if( $.browser.msie )
			return true;
		var imgsrc = $( this ).attr( "href" );
		/** resize image for screen (can be smaller than thumbnail
		var max_width = Math.round( $( window ).width() / 3 * 2 );
		var max_height = Math.round( $( window ).height() / 3 * 2 );
		$( "<img />" ).attr( {
			src:imgsrc
		} ).load( function() {
			var rate = this.width / this.height;
			if( max_height < this.height )
				var height = max_height;
			else
				height = this.height;
			var width = height * rate;
			dialogue.prompt( that, $( '<img src="' + imgsrc + '" width="' + width + '" height="' + height + '" />' ), 'image' );
		} ); */
		if( in_array( imgsrc, image_cache ) ) {
			dialogue.prompt( that, $( '<img src="' + imgsrc + '" width="480" height="640" />' ), 'image' );
		}
		else {
			$( "<img />" ).attr( {
				src:imgsrc
			} ).load( function() {
				dialogue.prompt( that, $( '<img src="' + imgsrc + '" width="480" height="640" />' ), 'image' );
			} );
		}
		return false;
	} );
	// cart
	$( "#cart_form thead input[type=checkbox]" ).click( function() {
		if( "on" == $( "#cart_form thead input[type=checkbox]:checked" ).val() )
			$( "#cart_form tbody input[name=checked_items[]]" ).each( function() {
				$( this ).attr( { checked:"checked" } );
			} );
		else
			$( "#cart_form tbody input[name=checked_items[]]" ).each( function() {
				$( this ).removeAttr( "checked" );
			} );
	} );
	$( "#cart_form .remove" ).click( function() {
		$( "#cart_form" ).attr( {
			action:$( this ).attr( "href" )
		} ).submit();
		return false;
	} );
} );
