function GoToSearchPage(uri, searchText) {
    if (searchText && typeof searchText === 'string' && !/^\s+$/.test(searchText)) {
        document.location.href = uri + searchText.replace(/^\s+/, "").replace(/\s+$/, "");
    }
}
function CancelEvent(e) {
    e.preventDefault();
    e.stopPropagation();
    e.stopImmediatePropagation();
    e.bubbles = false;
    e.cancelBubble = true;
    e.returnValue = false;
    return false;
}

/**
 * Functions for handling the scrolling of the blog teasers in the footer.
 */
var footerBlogsPosition = 0;
function slideFooterBlogs(change) {
	// check new position
	var newval = footerBlogsPosition + change;
	if (newval < 0)
		return; // too low
	if ($('#foot .blogs .blog' + (newval + 2)).size() < 1)
		return; // too high
	// move there
	$("#foot .blogs .contents .fw").animate( {
		left : -(295 * newval)
	}, 500);
	footerBlogsPosition = newval;
}

/**
 * Functions for handling the image grid (onHover) in the footer
 */
function recipegrid_hover(a, name, imgUrl, x, y) {
	// get grid
	var grid = $(a).parents('.recipegrid').get(0);
	var hover = $('.recipegrid-hover', grid);
	// calculate position 
	x -= 25; y -= 30;
	//var x = Math.max(-15, (index % 8) * 120 - 25);
	//var y = (Math.floor(index / 8)) * 90 - 30;
	var linkUrl = $(a).attr('href');
	// move hover div
	$(hover).show().css('left', x + 'px').css('top', y + 'px');
	//$('#foot-recipegrid-hover').show().css('left', x + 'px').css('top',	y + 'px');
	// set new data
	$('h4 a', hover).html(Hyphenator.hyphenate(name, 'sv'));
	$('img', hover).attr('src', imgUrl);
	$('a', hover).attr('href', linkUrl);
	return false;
}
function recipegrid_reload(grid, widths, rows, height, keyword) {
	// calculate url
	var date = new Date();
	var url = '/ajax/recipegrid/?widths=' + widths + "&rows=" + rows + "&height=" + height + "&keyword=" + keyword + "&" + date.getTime();
	$('.contents', grid).load(url);
	$('.makenew', grid).show();
}

/**
* Properties for predefined popup windows
*/
var popupClasses = {
	poll : "height=580,width=580,scrollbars=1,resizable=1",
	multipoll : "height=580,width=580,scrollbars=1,resizable=1",
	sendto : "height=700,width=580,scrollbars=1,resizable=1",
	popupPrint : "height=700,width=580,scrollbars=1,resizable=1",
	standard : "height=700,width=580,scrollbars=1,resizable=1",
	oldsite : "height=700,width=740,scrollbars=1,resizable=1"
};


/**
* Method used to submit form data to new windows.
*/
function submitToNewWindow(form, winName, noSubmit) {
	if (!winName)
		winName = "standard";
	if (form) {
		// get windows params
		var winParams = popupClasses[winName];
		if (winParams == null)
			winParams = popupClasses["standard"];
		// open new window
		newWindow = window.open("", winName, winParams);
		// submit to this window
		form.target = winName;
		if (noSubmit == true)
			return;
		form.submit();
	}
}

function CM8ShowAd() { } 

$(function() {
	var formid = '#sendemailform';
	$(formid).submit(function() {
	    var to_email = $(formid+' .to_email').val();
	    var message = $(formid+' .message').val();
	    var from_email = $(formid+' .from_email').val();
	    var from_name = $(formid+' .from_name').val();
	    var id = $(formid+' .id').val();
	    
	    $.ajaxSetup({ scriptCharset: "utf-8" , contentType: "application/json; charset=utf-8" });
	    $.getJSON(
	    		$(formid).attr('action'), 
	    		{ to_email: to_email, message: message, from_name: from_name, from_email: from_email, id: id },
	    		function(data, status){ 
	    			alert(data.msg);
	    			if(data.success) $(formid).hide();
	    		}
	    );
	    return false;
	});
});
$(function() {
	var formid = '#sendsmsform';
	$(formid).submit(function() {
	    var to = $(formid+' .to').val();
	    var type = $(formid+' .type').val();
	    var id = $(formid+' .id').val();
	    $.getJSON(
	    		$(formid).attr('action'), 
	    		{ to: to, id: id, type: type },
	    		function(data, status){ 
	    			alert(data.msg);
	    			if(data.success) $(formid).hide();
	    		}
	    );
	    return false;
	});
});


// - - wine list - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

jQuery.fn.wineList = function(args) {
	this.each(function() {
		args.elem = $(this);
		new WineList(args);
	});
};

function WineList(args) {
	var wl = this;
	// org data from hash
	var orgdata = {}
	try {
		var orgdata_raw = window.location.hash;
		if(orgdata_raw.substr(0,1) == '#') orgdata_raw = orgdata_raw.substr(1);
		if(orgdata_raw) orgdata = eval('(' + decodeURIComponent(orgdata_raw) + ')');
	} catch(e) {
		// ignore errors, if anything is wrong we will not use hash args
	}
	// how to init params
	this.initParam = function(arg, param, defval) {
		if(param && typeof orgdata[param] != 'undefined')
			return orgdata[param];
		if(typeof args[arg] != 'undefined')
			return args[arg];
		return defval;
	};
	// store current elem and make shortcut for searching it
	wl.elem = args.elem; 
	var e = wl.elem;
	
	// main search function
	this.update = function(noScrolling) {
		var data = {
			q: wl.query,
			t: wl.type,
			p: wl.page,
			ps: wl.pageSize,
			gw: wl.goodWith,
			fp: wl.priceMin,
			tp: wl.priceMax,
			pr: wl.priceRange,
			s: wl.sort,
			sd: (wl.sortDesc ? 'desc' : 'asc')
		};
		if( data.q || data.t || args.url ) {
			// save window state
			if(!( wl.noScrolling || noScrolling))
				window.location.hash = encodeURIComponent( array2json( data ) );
			// show loading screen
			window.clearTimeout( wl.timerId );
			e.find('.contents').show();	
			e.find('.contents .status').html('<i><img src="/images/gfx/ajax-progress1.gif" alt="laddar..." /> Laddar viner...</i>').addClass('loading');
			e.find('.contents table').addClass('opacity50'); 
			// perform search
			$.getJSON(wl.url, data, function(data, status) {
				// status line
				if(data.hitcount > 0)
					e.find('.contents .status').html(
							'Visar ' + (((data.page-1) * data.pagesize)+1) + 
							'-' + Math.min((data.page*data.pagesize), data.hitcount) + 
							' av <strong>' + data.hitcount + '</strong> viner.'
					).removeClass('loading');
				else
					e.find('.contents .status').html( 'Inga träffar.' ).removeClass('loading'); // data.query.generatedQuery
				// remove old results
				e.find('.contents .list tr:not(.template)').remove();
				// build results list
				$.each(data.hitlist, function(nr, wine) {
					var row = e.find('.contents .list tr.template').clone();
					row.removeClass('template');
					$('.type img', row).attr( 'src', '/images/gfx/wine-icon-' + wine.type + '.png' );
					$('a', row).attr( 'href', wine.link );
					$('.title a', row).html( wine.title );
					$('.subtitle', row).html( wine.subtitle );
					$('.price', row).html( wine.price + ' kr' );
					$('.score img', row).attr( 'src', '/images/gfx/ws-score-' + wine.score + '.png' );
					if( wine.linkCount < 1) 
						$('.linkcount img', row).hide();
					else
						$('.linkcount img', row).attr('title', 'Har ' + (wine.linkCount == 1 ? 'ett kopplat' : wine.linkCount + ' kopplade') + ' recept.');
					e.find('.contents .list').append( row );
				});
				e.find('table').removeClass('opacity50');
				// update paging
				wl.setPage( data.page, data.pagecount );
				// scroll to start of list
				//var startOfList = e.find('.contents .listhead').get(0);
				//if(!startOfList) startOfList = e.get(0);
				//startOfList.scrollIntoView();
				if(!( wl.noScrolling || noScrolling))
					e.get(0).scrollIntoView();
			});
		}
		else {
			e.find('.contents').hide();
		}
	};
	this.setType = function(type) {
		// clear selected tab
		e.find('.searchTabList li.active').removeClass('active');
		if(type) {
			// make clicked tab active
			e.find('.searchTabList li.' + type).addClass('active');
		}
		// ie needs to be forced to redraw the tabs, so we have to set the bg color manually
		if($.browser.msie) { 
			e.find('.searchTabList li a').css('background-color', '#2C2C28');
			e.find('.searchTabList li.active a').css('background-color', '#fff');
		}
		// save to var
		wl.type = type;
	}; 
	this.setQuery = function(query) {
		if( arguments.length == 0 ) {
			query = e.find('form .wl-q').attr('title');
			wl.query = '';
		} else {
			wl.query = query;
		}
		e.find('form .wl-q').val( query );
	};
	this.setSort = function(field, desc) {
		// default values
		if( arguments.length == 0 ) { field = 'score'; desc = true; }
		// select correct column
		e.find('.contents .listhead li').removeClass('active').removeClass('desc');
		e.find('.contents .listhead li.' + field).addClass('active');
		// calc direction
		if(arguments.length == 1) {
			if(field == wl.sort)
				// reverse current direction
				desc = ! wl.sortDesc;
			else
				// new default direction from column
				desc = e.find('.contents .listhead li.active').hasClass('default-sort-desc');
		}
		// set direction in col
		if(desc) e.find('.contents .listhead li.active').addClass('desc');
		// save
		wl.sort = field;
		wl.sortDesc = desc;
	}; 
	
	this.setGoodWith = function(foodType) {
		if( arguments.length == 0 ) foodType = 'none';
		wl.goodWith = foodType;
		if(!foodType) foodType = 'none';
		e.find('.filters .goodwith li').removeClass('active');
		e.find('.filters .goodwith li.' + foodType).addClass('active');
	};
	
	this.setPriceRange = function(range) {
		if( arguments.length == 0 ) range = 'none';
		wl.priceRange = range;
		if(!range) range = 'none';
		if(range == 'range1') { wl.priceMin = -1; wl.priceMax = 99; }
		else if(range == 'range2') { wl.priceMin = 100; wl.priceMax = 200; }
		else if(range == 'range3') { wl.priceMin = 201; wl.priceMax = -1; }
		else { wl.priceMin = -1; wl.priceMax = -1; }
		e.find('.filters .pricerange li').removeClass('active');
		e.find('.filters .pricerange li.' + range).addClass('active');
	};
	
	this.setPage = function(page, pageCount) {
		wl.page = page;
		// next/prev
		e.find('.paging .left div').hide().filter('.' + (page == 1 ? 'disabled' : 'enabled')).show();
		e.find('.paging .right div').hide().filter('.' + (page == pageCount ? 'disabled' : 'enabled')).show();
		// list of pages
		e.find('.paging .center').html('');
		var first = Math.max(1, page - 5);
		var last = Math.min(pageCount, first + 9);
		if( first != 1 )
			e.find('.paging .center').append( '<a href="">1</a> .. ');
		for(var x = first; x <= last; x++) {
			if(x == page)
				e.find('.paging .center').append( '<span class="selected br5">' + x + '</span> ');
			else
				e.find('.paging .center').append( '<a href="">' + x + '</a> ');
		}
		if( last != pageCount )
			e.find('.paging .center').append( '.. <a href="">'+pageCount+'</a> ');
		// apply listeners
		e.find('.paging .center a').click(function() {
			wl.page = $(this).text(); wl.update(); return false;
		});
	}
	
	// init
	wl.url = wl.initParam('url', '', '');
	if(wl.url == '') wl.url = '/ajax/winesearch';
	
	// vars to keep track of search/sort/pageing state
	wl.timerId = 0;
	wl.pageSize = wl.initParam('pageSize', 'ps', -1);
	wl.sort = wl.initParam('sort', 's', '');
	wl.priceMin = wl.initParam('priceMin', 'fp', -1);
	wl.priceMax = wl.initParam('priceMax', 'tp', -1);
	wl.noScrolling = wl.initParam('noScrolling', '', 0);
	// some values must be set by functions
	wl.setQuery( wl.initParam('query', 'q', '') );
	wl.setType( wl.initParam('type', 't', '') );
	wl.setGoodWith( wl.initParam('goodWith', 'gw', '') );
	wl.setPriceRange( wl.initParam('priceRange', 'pr', 'none') );
	wl.setSort( wl.initParam('sort', 's', ''), wl.initParam('sortDesc', 'sd', '') );
	wl.setPage( wl.initParam('page', 'p', 1), wl.initParam('pageCount', '', 1) );
	
	// attach listeners
	e.find('.paging .left a').click(function() {
		wl.page--; wl.update(); return false;
	});
	e.find('.paging .right a').click(function() {
		wl.page++; wl.update(); return false;
	});	
	e.find('form .wl-q').keyup(function() {
		// only update after 500 ms
		window.clearTimeout( wl.timerId );
		wl.timerId = window.setTimeout( function() { e.find('form .wl-q').change(); }, 500 );
	}).change(function() {
		// clear to defaults
		wl.setType(); 
		wl.setSort();
		wl.setPriceRange();
		wl.setGoodWith();			
		// get new search string	 
		var newQuery = e.find('form .wl-q').val();
		if( newQuery == e.find('form .wl-q').attr('title') ) newQuery = ''; // default/tooltip value
		// changed?
		if( wl.query != newQuery ) {
			wl.query = newQuery;
			wl.update(); 
		} 
	});
	// tabs
	e.find('.searchTabList li a').click(function() {
		// clear to defaults
		wl.setQuery(); 
		wl.setSort();
		wl.setPriceRange();
		wl.setGoodWith();
		wl.page = 1;
		// set type and search
		wl.setType( $(this).attr('href').substr(3) );
		wl.update();
		return false;
	});
	// sorting
	e.find('.contents .listhead a').click(function() {
		wl.setSort( $(this).attr('class') );
		wl.page = 1;
		wl.update();
		return false;
	});
	// good with
	e.find('.filters .goodwith li a').click(function() {
		wl.setGoodWith( $(this).attr('href').substr(4) );
		wl.page = 1;
		wl.update();
		return false;
	});
	// price range
	e.find('.filters .pricerange li a').click(function() {
		wl.setPriceRange( $(this).attr('href').substr(4) );
		wl.page = 1;
		wl.update();
		return false;
	});
	// search button
	e.find('.wl-submit').click(function() {
		wl.update();
		return false; 
	});		
	
	
	// populate list
	wl.update( true );
	
};

/**
 * Converts the given data structure to a JSON string.
 * Argument: arr - The data structure that must be converted to JSON
 * Example: var json_string = array2json(['e', {pluribus: 'unum'}]);
 * 			var json = array2json({"success":"Sweet","failure":false,"empty_array":[],"numbers":[1,2,3],"info":{"name":"Binny","site":"http:\/\/www.openjs.com\/"}});
 * http://www.openjs.com/scripts/data/json_encode.php
 */
function array2json(arr) {
    var parts = [];
    var is_list = (Object.prototype.toString.apply(arr) === '[object Array]');

    for(var key in arr) {
    	var value = arr[key];
        if(typeof value == "object") { //Custom handling for arrays
            if(is_list) parts.push(array2json(value)); /* :RECURSION: */
            else parts[key] = array2json(value); /* :RECURSION: */
        } else {
            var str = "";
            if(!is_list) str = '"' + key + '":';

            //Custom handling for multiple data types
            if(typeof value == "number") str += value; //Numbers
            else if(value === false) str += 'false'; //The booleans
            else if(value === true) str += 'true';
            else str += '"' + value + '"'; //All other things
            // :TODO: Is there any more datatype we should be in the lookout for? (Functions?)

            parts.push(str);
        }
    }
    var json = parts.join(",");
    
    if(is_list) return '[' + json + ']';//Return numerical JSON
    return '{' + json + '}';//Return associative JSON
}


