$(document).ready(function(){
	//Init fieldhints
	$(".defaultValue").defaultvalue();
	
	//Bind Contact choser event
	jQuery('#btnContactList, #contact_choser .btnClose span').click(contactChoser_click);
	//Bind Search box event
	$('#widgetSearch input.searchText').keyup(searchBox_keyup);
	$('#widgetSearch button.searchBtn').click(searchBox_click);
	$('.searchClose').live('click',function(){searchResult_hide(); contactChoser_hide();});

	//Facebox init
	facebox_init();
	
	//HIde elements that needs hiding
	$(".hide").hide();
});

//----------------------------------------------------------------------------------------------//

/*
*	Default Value plugin (Form Field Hint thingy...)
*/
(function($) {
	$.fn.defaultvalue = function()
	{
		this.each(function()
		{
			var el = $(this);
			var value = el.attr("rel");
			
			if(el.val()=="") el.val(value);
			if(el.val()==value) el.addClass("dim");
			
			el.focus(function()
			{
				if(el.val() == value) el.val("");
				el.removeClass("dim");
			});
			el.blur(function()
			{
				if(el.val() == "")
				{
					el.addClass("dim");
					el.val(value);
				}				
			});
		});
		return this;
	}
})(jQuery)

//----------------------------------------------------------------------------------------------//

/*
* Facebox Init
*/
function facebox_init(){
	jQuery('#btnLogin').attr('href', "#login");
	jQuery('a[rel*=facebox]').facebox({
		loading_image : '/includes/style/images/facebox/loading.gif',
		close_image   : '/includes/style/images/facebox/closelabel.gif.png',
		opacity      : 0.8
	})
}

//----------------------------------------------------------------------------------------------//

/*
*	Contact Chooser widget init
*/
function contactChoser_click(){
	searchResult_hide();
	jQuery('#contact_choser').slideToggle('fast');
	//Hide div if clicked outside
	$(document).click(function(e){
		if ( $(e.target).closest("#contact_choser").get(0) == null ){ 
			contactChoser_hide();
		}
	});
	return false;
}

function contactChoser_hide(){
	$("#contact_choser").slideUp('fast'); 
}

//----------------------------------------------------------------------------------------------//
	
/*
* Search box functions
*/
var prevSearchString
function searchBox_keyup(event){
	contactChoser_hide();
	if (event.keyCode == '13') {
		event.preventDefault();
	}
	var search_val = $.trim($('#widgetSearch input.searchText').val());
	if(search_val.length > 2){ 
		if(search_val != prevSearchString){
			prevSearchString = search_val;
			ajax_search(search_val); 
		}
	}else{
		prevSearchString = "";
		searchResult_hide();
	}
	return false;
}

function searchResult_hide(){
	$("#search_result").slideUp('fast'); 
}

function searchBox_click(){
	if($("#search_result").is(":hidden")){
		var search_val = $.trim($('#widgetSearch input.searchText').val());
		ajax_search(search_val);
	}
}

var timeout = null;
function ajax_search(search_val) {
    $("#searchBoxLoader").show();
	$(document).click(function(e){
		if ( $(e.target).closest("#search_result, #widgetSearch").get(0) == null ){ 
			searchResult_hide();
		}
	});
	//jQuery('#search_result').slideUp('fast');
	if (timeout) clearTimeout(timeout);
	timeout = setTimeout(function(){
        //$("#throbber").show();
        //$("#search_result").slideUp(); //Hide results DIV
		var ajax_search_REQ=$.post("/article/ajaxSearch.asp", { "s": search_val },function(jsondata){
			if (ajax_search_REQ) {ajax_search_REQ.abort();}
			$("#searchBoxLoader").hide();
			switch(jsondata.errorLevel){
				case 0:	$("#search_result .search_result_content").html(format_search_result(jsondata.result, search_val)); break;
				case 1: $("#search_result .search_result_content").html('<div class="noResult"><br>No products matched your query.<br><br></div>'); break;
			}
			$("#search_result").slideDown('fast');
            //$("#throbber").hide();
        },"json");
    }, 200);
}

function format_search_result(jsondata,search_val) {
        var resultLength = jsondata.length
        if (resultLength == 0) {
            return '<h2>Din sökning gav inga träffar...</h2>';
        }
        else {
          var productsFound = "";
		  if (resultLength == 1) {productsFound = '1 product found';}
          else {productsFound = resultLength + ' products found';}
          html = '<div class="clear"><h2 class="fLeft">' + productsFound + '</h2><span class="searchClose">Close</span></div>';
		  for (i in jsondata){
              html+='<div class="searchResultArticle"><div class="borderBox">';
			  html+='<div class="articleImage" ><a href="/article/details.asp?articleid=' + jsondata[i].ArticleId + '"><img src="/dataimages/' + jsondata[i].ArticleImageId + '/85x70.JPG" /></a></div>';
			  html+='<a href="/article/details.asp?articleid=' + jsondata[i].ArticleId + '"><span class="articleName">' + jsondata[i].ArticleName + '</span></a></div>';
			  //ArticleImageId == -1 means it is an ArticleRedirect (genväg)
			  if(jsondata[i].ArticleForSale){
				  if(jsondata[i].ArticleImageId == -1){
					html+='<a class="btnBuy" title="Buy ' + jsondata[i].ArticleName + '" href="/article/details.asp?articleid=' + jsondata[i].ArticleId + '">' + jsondata[i].ArticlePrice + '</a>'
				  }else{
					html+='<a class="btnBuy" title="Buy ' + jsondata[i].ArticleName + '" href="/article/quickbuy.asp?ArticleId=' + jsondata[i].ArticleId + '">' + jsondata[i].ArticlePrice + '</a>'
				  }
			  }
              html+='</div>';
          }
          return html;
        }
}

//----------------------------------------------------------------------------------------------//
/*
*	Article Details Page
*/

$(document).ready(function(){

});

//----------------------------------------------------------------------------------------------//

/*
*	Helper Popups (Jquery Bubble Popups)
*/
jQuery(document).ready(function (){
		// Initialize all .helper elements on the page and 
		// load content using the rel-attribute of the element.
		
		jQuery(".helper").map(function(index, domElm){
			var contents = helpset[ jQuery(domElm).attr("rel") ];
			jQuery(domElm).CreateBubblePopup({
							themeName: 'grey',
							themePath: '/include/style/themes', 
							alwaysVisible: true, 
							openingSpeed: 175,
							closingSpeed: 175,
							closingDelay: 100,
							manageMouseEvents: true,
							innerHtml: contents,
							width: '290px',
							tail: {align:'center'},
			});
		});
		
});
var helpset = new Array();
helpset["paramhelp"] = '<strong><u>All types  of contact lenses:</u><br/>BC/Radius </strong> = Base curve<br/><strong>DIA</strong> = Diameter<br/><strong>Sphere/SPH/PWR</strong> = Power<br/><strong>Visus</strong> = Not applicable, ignore<br/><br/><strong><u>Only toric lenses:</u><br/>Cyl</strong> = Cylinder (<em>e.g. "-0.75"</em>)<br/><strong>Ax</strong> = Axis (<em>e.g. &quot;90&quot;</em>)<br/><span style="margin-left:28px;">N.B. Axis 0 och axis 180 is the same value.</span><br/><br/><strong><u>Only progressive lenses:</u><br/>Add/Addition</strong> = Extra power (<em>e.g. "+2.00" or "Low"</em>)'
helpset["campaign"] = 'With a campaign code you get access to special discounts and offers. To activate the campaign code you enter the code in the box and click "Activate". Campaign codes can be found in connection to special events and campaigns.'
helpset["repackage"] = 'If you live in a flat or by some other circumstance have a narrow letterbox (less than 3cm in height), you can choose the service "Thin package". Your order will then be packaged in the thinnest way possible. Letterboxes vary a lot in size so we cannot guarantee that our special package will fit all letterboxes. Thin packaging cannot be done when the order contains lens solution or if the order is too large for our special pack.'

//------------------------------------------------------------------------------------------------------------//
/*
*	Tryggt och Säkert
*/
$(document).ready(function(){
	$('#tryggt_sakert #canvas .box_container').each(function(index, elm){
		var readMore = $('<a href="#" class="readMore">Read more...</a>');
		$(readMore).click(function(event){
			event.preventDefault();
			var link = this;
			var container = elm;
			var textBlock = $(elm).find('.text_content')
			$(container).find('.closeBtn').click(function(event){ event.preventDefault(); $.mask.close(); });
			$(link).hide();
			$(container).addClass('show');
			
			//$(document).mask();
			$(elm).expose({	color: '#fff',
							opacity:0.0,
							loadSpeed: 'fast',
							closeSpeed: 'fast',
							onBeforeLoad: function(){ 	$(elm).css('background-color','#fff');
														$(textBlock).fadeIn();
									},
							onBeforeClose: function(){ 	$(container).removeClass('show');
														$(textBlock).hide(); 
														$(link).show();
											}
							});
		});
		$(elm).append(readMore);
	});
});
