/* SAS Smörgåsbord */

var sbGlobal = new Array();
sbGlobal['pos'] = 'SE';

// default outday and number of days
sbGlobal['outday'] = 4;
sbGlobal['days'] = 3;

sbGlobal['steps'] = 100;
sbGlobal['priceinfo'] = 'revenue';
sbGlobal['config'] = 0;
sbGlobal['direct'] = 0;
sbGlobal['lng'] = '';
sbGlobal['area'] = '';
sbGlobal['servicefee'] = '';
sbGlobal['servicefeeamt'] = '';


var timer;
var timerTicking = 0;
var gridLoading = 0;

$(document).ready(function() {
    /*
	var blank = new Image();
	blank.src = 'images/spacer.gif';
    var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
    if (badBrowser) {
        // get all pngs on page
        $('img[src$=.png]').each(function() {
           if (!$(this).complete) {
              $(this).onload = function() { fixPng($(this)) };
           } else {
              fixPng($(this));
           }
        });
    }
    */
	
	Cufon.replace('h1');

	// get qstring
	// populate form from qstring
    var qStr = window.location.search;
    if(qStr) {
        qStr = qStr.substring(1);
        var a = qStr.split('&');
        if(a.length) {
            for(var i=0;i<a.length;i++) {
                var index = a[i].indexOf('=');
                var key = a[i].substring(0,index);
                var val = a[i].substring(index+1);        
                if(key && val) {
                    sbGlobal[key] = val;  
					if($("input[name="+key+"]").attr('type') != 'radio') {
						$("input[name="+key+"]").val(val);
						$("select[name="+key+"]").val(val);
					}
                }
            }
        }
    }
    
    if(sbGlobal['WT.mc_id']) {
        sbGlobal['wt_mc_id'] = sbGlobal['WT.mc_id'];
    }
    
	if(sbGlobal['travel'] == 'roundtrip') {
		travel();
	};
		
	// big5
	if(sbGlobal['mode'] == 'big5') {
		sbGlobal['config'] = 98;
		// will overwrite values from get
		//sbGlobal['outday'] = 4;
		//sbGlobal['days'] = 3;
	}
	
    // show eurobonus selections
	if(sbGlobal['eurobonus'] == 1) {
	    $("#eurobonusfields").show();
	}
	
	// set roundtrip if priceinfo=eurobonus
	if(sbGlobal['priceinfo'] == 'eurobonus') {
		//$("form#tripForm select[name=travel]").val('roundtrip');
		trReplace('eurobonus');
		travel();
	} else {
    	populateOrg();	
	}
	
	// set default in form
	$("form#tripForm input[value="+sbGlobal['priceinfo']+"]:radio").attr('checked','checked');
	
	// direct (blue1)
    $("input[name=direct]:radio").each(function(i,v) {
        if($(this).val() == sbGlobal['direct']) {
            $(this).attr('checked','checked');
        }
    });

	$("div.arrow").bind('mouseenter',function(e) {
		if(!gridLoading) $(this).addClass('over');
	});
	
	$("div.arrow").bind('mouseleave',function(e) {
		if(!gridLoading) $(this).removeClass('over');
	});


    $("form#tripForm select[name=outday]").val(sbGlobal['outday']);
	
	populateDays();
		
	
	// events
	$("div.arrow.forward").click(function() {
		if(!gridLoading) moveCalendar('forward');
	});
	
	$("div.arrow.back").click(function() {
		if(!gridLoading) moveCalendar('back');
	});

    // big5 area
	if($("form#tripForm select[name=area]").length) {
		if(!sbGlobal['area']) {
			$("form#tripForm select[name=area]").val('eu');
		}
		$("form#tripForm select[name=area]").change(travel);
	}

	// oneway roundtrip
	$("form#tripForm select[name=travel]").change(travel);
	
	$("form#tripForm select[name=travel]").mouseenter(function() {
		var travel = $("form#tripForm select[name=travel] option:selected").val();
		var priceinfo = $("form#tripForm input[name=priceinfo]:checked").val();
		// eurobonus is always roundtrip
		if(priceinfo == 'eurobonus') {
			//if(travel == 'oneway') {
				$("#interContMsg").show();
			//}
		}
	});
	
	$("form#tripForm select[name=travel]").mouseleave(function() {
		$("#interContMsg").hide();
	});
	
	$("form#tripForm select[name=outday]").change(function() {
		populateDays(1);
	});
	
	$("form#tripForm select").bind('change',function() {
		loadGrid(false,false);
	});
	
    $("input[name=priceinfo]", "form#tripForm").bind(($.browser.msie ? "click" : "change"),function(e) {
		trReplace();
		loadGrid(false,false);
    });

    // direct (blue1)
    $("input[name=direct]").bind(($.browser.msie ? "click" : "change"),function(e) {
        sbGlobal['direct'] = $(this).val();
		loadGrid(false,false);
    });
	
	$("div#container div.close a, div#bodyImage").bind('click', function() {
		if(sbGlobal['mode'] == 'blue1') {
			top.location = 'http://www.blue1.com';
		} else {
			if($("form#tripForm input[name=iframe]").val() != 1) {
				var ref = document.referrer;
				ref = ref.replace("openbuf","noopenbuf");
				top.location = ref;
			}
		}
	});

	$("div#travellers a, div#big-transparent").bind('click', function() {
		travellers('hide');
	});

	$("#slider-price-bar").slider({
		step: sbGlobal['steps'],
		slide: slidePrice,
		change: slidePrice,
		stop: slidePrice
		
	});

	$("div#grid table thead th.selectprice a").click(function() {
		$(document).scrollTop(0);
		destinationSelector('show');
	});
	
	$("div#destination-done1, div#destination-done2").click(function() {
		destinationSelector('hide');
		$(document).scrollTop(0);
	});
	
	$("div.button.load").click(function() {
		loadGrid(false,false,0,1);
	});

	$("div.button.save").click(destinationsStickySave);
	
	$("div#deeplink").click(function() {
	    deepLink()
    });
	
	$("a#clearAllDestinations").click(destinationsClearAll);
	
	$("div#destinations fieldset[name=categories] input[type=checkbox]").click(destinationsCategory);
	
	//setTimeout(function() { $("div#msgAshes").hide(); },5000);
	
});

function fixPng(png) {
    // get src
    var src = png.src;
    // set width and height
    if (!png.style.width) { png.style.width = $(png).width(); }
    if (!png.style.height) { png.style.height = $(png).height(); }
    // replace by blank image
    png.onload = function() { };
    png.src = blank.src;
    // set filter (display original image)
    png.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
}

function travel(init) {

	var travel = $("form#tripForm select[name=travel] option:selected").val();
	var area = $("form#tripForm select[name=area] option:selected").val();
    if(area == 'domestic' || area == 'eu') {
        //travel = 'oneway';
        //$("form#tripForm select[name=travel]").val(travel)
    } else if(area == 'int') {
        travel = 'roundtrip';
        $("form#tripForm select[name=travel]").val(travel)
    }
	var priceinfo = $("form#tripForm input[name=priceinfo]:checked").val();
	
	if(!travel) return false;

	if(init != 1) {
		$("div.month, div.week").removeClass('selected');
	}

	// eurobonus is always roundtrip
	if(priceinfo == 'eurobonus') {
		//if(travel == 'oneway') {
		//	$("#interContMsg").show();
		//}
		$("form#tripForm select[name=travel]").val('roundtrip');
		travel = 'roundtrip';
	//} else {
		//$("#interContMsg").hide();
	}

	clearTimeout(timer);
	timerTicking = 0;

	var t1 = $("form#tripForm fieldset#roundtrip");
	var t2 = $("div#dateselector p span,"+
		       "div#weeks, "+
		       "div.arrow.week");
	var t3 = $("div#dateselector, div#slide-wrapper");
	var t4 = $("div#dates");
	var duration = 500;
	if(travel == 'oneway') {
		t1.fadeOut(duration,moveIframe);
		t2.fadeIn(duration,function() { t2.show(); });
		t3.animate({height: "70px" },duration);
		t4.animate({height: "65px" },duration);
	} else if(travel == 'roundtrip') {
		t1.fadeIn(duration,moveIframe);
		t2.fadeOut(duration,function() { t2.hide(); });
		t3.animate({height: "40px" },duration);
		t4.animate({height: "35px" },duration);
	}
	
	
}

function moveIframe() {
	// move big5 iframe
	
	var fhTop = $("div#wrapper-grid").position().top;
	fhTop += 21;
	$("#flighthotel").css('top',fhTop+'px');
}

function moveCalendar(dir) {
	// reset timer
	//clearTimeout(timer);
	// move weeks
	var m = $("div#weeks");
	var mPrevLeft = parseInt(m.css('left'));
	var newLeft = mPrevLeft;
	if(dir == 'forward') newLeft -= 600;
	else newLeft += 600;
	mNewLeft = newLeft+'px';
	m.animate({left:mNewLeft},500);
	// move months
	var w = $("div#months");
	var wPrevLeft = parseInt(w.css('left'));
	var newLeft = wPrevLeft;
	if(dir == 'forward') newLeft -= 95;
	else newLeft += 95;
	wNewLeft = newLeft+'px';
	w.animate({left:wNewLeft},500);
	
	//if(!$("div.months.selected").length) {
	if(timerTicking == 0) {
		timerTicking = 1;
		timer = setTimeout(function () {
			//w.animate({left:'0px'},500);
			//m.animate({left:'0px'},500);
			w.animate({left:wPrevLeft},500);
			m.animate({left:mPrevLeft},500);
			//alert(wNewLeft+' '+mNewLeft);
			timerTicking = 0;
		},10000);
	}
	//} else {
	//	clearTimeout(timer);
	//}
}		

function moveCaltoWeek(week,month) {
	//alert(week+'\n'+month);
    //if(week > 0 && !gridLoading) {
	if(week > 0) {
    	// reset timer
		//clearTimeout(timer);
		// move weeks
		var w = $("div#weeks");
		
        /* stefans old function
		var m = $("div#weeks");
		var prevLeft = parseInt(m.css('left'));
		var newLeft = prevLeft;
		newLeft = -140*(week-4);
		newLeft = newLeft+'px';
		*/
		
		// peter new functions 2010-03-05
		/*
		var numWeeks = m.children('div.week').length-2;
		var prevLeft = parseInt(m.css('left'));
		var newLeft = prevLeft;
		newLeft -= 130*(week-(52-numWeeks));
		newLeft = newLeft+'px';
		*/

		// third try		
		var newLeft = 0-parseInt($("div.week."+week).position().left);
        if($("div#weeks").css('display') == 'none') {
            var index = $("div.week").index($("div.week."+week));
            newLeft = 0-((index-2)*130);
            
        }
		newLeft += 130;
		newLeft = newLeft+'px';
		//alert(newLeft);
        // move weeks
		w.animate({left:newLeft},500);
		// select 1st week of month
		loadGrid(week);
	}
	
	if(month) {
		var m = $("div#months");
		var mLeft = 0;
		if($("div.month."+month).position()) {
			mLeft = $("div.month."+month).position().left;
		}
		var newLeft = 0-parseInt(mLeft);
		newLeft += 95;
		newLeft = newLeft+'px';
		
		//alert(newLeft);
        // move weeks
		m.animate({left:newLeft},500);
	
	}
	
}		

function loadCalendar() {
	var m = $("div#months");
	var w = $("div#weeks");
	m.empty();
	w.empty();
	
	$.getJSON("calendar.php",{
		pos: sbGlobal['pos'],
		lng: sbGlobal['lng'],
		config: sbGlobal['config'],
		direct: sbGlobal['direct'],
		mode: sbGlobal['mode']
	},function(data) {
		var monthName;
		$.each(data,function(i,date) {
			
			// select first week if ?month=
            if(!sbGlobal['week'] && i == 1 && sbGlobal['travel'] != 'roundtrip') {
                sbGlobal['week'] = date.week;
                sbGlobal['month'] = date.month;
            } else if(!sbGlobal['month'] && i == 1 && sbGlobal['travel'] == 'roundtrip') {
                sbGlobal['week'] = date.week;
                sbGlobal['month'] = date.month;
			}
			
			if(monthName != date.monthName) {
				// create month
				var div = $('<div></div>').addClass('month')
				                          .addClass(date.monthName)
				                          .attr('rel',date.month);
                if(date.big5) {
                    div.addClass('big5');
                }
                
				var left = $('<div></div>').addClass('left');
				var right = $('<div></div>').addClass('right');
				var name = $('<div></div>').addClass('name')
				                           .text(date.monthName);
				div.append(left)
				   .append(name)
				   .append(right);				
				// month click
				div.click(function() {
					$("div.month").removeClass('selected');
					var travel = $("form#tripForm select[name=travel] option:selected").val();
					clearTimeout(timer);
					timerTicking = 0;
					if(travel == 'oneway') {
						moveCaltoWeek(date.week,date.monthName);
					} else if(travel == 'roundtrip') {
						if(!gridLoading) {
							$(this).addClass('selected');
							loadGrid(date.week,$(this).attr('rel'));
						}						
					}
				});
				// preseleted
    			if(sbGlobal['month'] == date.month) {
    				div.addClass('selected');
    				if(sbGlobal['week'] == undefined) {
    				    sbGlobal['week'] = date.week;
				    }
    			}
				m.append(div);
				monthName = date.monthName;
			}
			
			// create week
			var div = $('<div></div>');
			div.addClass('week');
			div.attr('rel', date.monthName);
			div.addClass(date.week);
			var left = $('<div></div>');
			left.addClass('left');
			var right = $('<div></div>');
			right.addClass('right');
			var name = $('<div></div>');
			name.addClass('name');
			name.text(lblWk+" "+date.week+", "+date.monday+" - "+date.sunday);
			div.append(left);
			div.append(name);
			div.append(right);
			
			// preseleted			
			if(sbGlobal['week'] == date.week) {
				sbGlobal['month'] = date.monthName;
				div.addClass('selected');
			    // mark month
				$("div.month").each(function() {
					if($(this).text() == date.monthName) {
						if(!$(this).hasClass('selected')) {
							$(this).addClass('selected');
						}
					}
				});
			}

			div.click(function() {
				clearTimeout(timer);
				timerTicking = 0;
				if(!$(this).hasClass('selected')) {
				    if(!gridLoading) {
    					$("div.week").removeClass('selected');
						$("div.month").removeClass('selected');

	    				$(this).addClass('selected');
	    				loadGrid(date.week,date.month);
	    				sbGlobal['week'] = date.week;				
						moveCaltoWeek(date.week,date.monthName);

    				}
				}
				// mark month
				var monthName = $(this).attr('rel');
				$("div.month").each(function() {
					if($(this).text() == monthName) {
						if(!$(this).hasClass('selected')) {
							$(this).addClass('selected');
						}
					}
				});
			});				
			w.append(div);

		});
		
		$(".month, .week").bind('mouseenter',function(e) {
			if(!gridLoading) $(this).addClass('over');
		});

		$(".month, .week").bind('mouseleave',function(e) {
			//if(!gridLoading) 
			$(this).removeClass('over');
		});
		moveCaltoWeek(sbGlobal['week'], sbGlobal['month']);
		travel(1);
		
	});
}

function loadGrid(week,month,fav,stickyfav) {
    if(gridLoading) return false;

	$("table#border-top").hide();
	
    var travel = $("form#tripForm select[name=travel] option:selected").val();
    var area = $("form#tripForm select[name=area] option:selected").val();    
	var org = $("form#tripForm select[name=org] option:selected").val();
	var outday = $("form#tripForm select[name=outday] option:selected").val();
	var days = $("form#tripForm select[name=days] option:selected").val();
	var priceinfo = $("form#tripForm input[name=priceinfo]:checked").val();
	
	
	if(!fav) fav = 0;
	if(!stickyfav) stickyfav = 0;
	
	$("div#footer-controls").hide();
	$("table#grid-table").hide();
	$("div#throbber").show();
	$("div#msgbox").hide();


    if(travel == 'roundtrip') {
        $("table#grid-table").removeClass('oneway').addClass('roundtrip');
    } else {
        $("table#grid-table").removeClass('roundtrip').addClass('oneway');
    }

	$(document).scrollTop(0);

    if(!week) {
        if(sbGlobal['week']) {
            week = sbGlobal['week'];
        }
    }

    if(!month) {
        if(week) {
           var monthName = $("div."+week).attr('rel');
           month = $("div."+monthName).attr('rel');
       } else if(sbGlobal['month']) {
            month = sbGlobal['month'];
        }
    }
	
	if(!org) org = sbGlobal['org'];
	if(week) sbGlobal['week'] = week;
	if(month) sbGlobal['month'] = month;
	
	if(!org) {
		$("div#wrapper-grid").hide();
	} else {
		$("div#wrapper-grid").show();
				
	}
		
	if((travel == 'oneway' && (!week || week <= 0)) ||
	   (travel == 'roundtrip' && ((!month || month <= 0) || !outday || !days)) ||
	   !org
	   ) {
		$("div#grid").hide();
		gridLoading = 0;
		return false;
	} else {
		$("div#grid").show();
	}
	
    // marked selected
	$("div.month[rel="+month+"]").addClass('selected');
	$("div.week."+week).addClass('selected');
	// empty grid header	
	var t = $("#gridcontent");
	t.empty();
	$("table#grid-table thead th:gt(0)").remove();

	var url;
	if(travel == 'oneway') {
    	url = 'json_sb_ow.php';
	} else if(travel == 'roundtrip') {
	    url = 'json_sb_rt.php';
	}

    var t = $("#gridcontent");
    t.empty();

    gridLoading = 1;
	// disable controls 
	$("div#selections input, div#selections select").attr('disabled','disabled');

	$.getJSON(url,
		{	
			org: org,
			week: week,
		    month: month,
			pos: sbGlobal['pos'],
			lng: sbGlobal['lng'],
			days: days,
			outday: outday,
			fav: fav,
			stickyfav: stickyfav,
			servicefee: sbGlobal['servicefee'],
			servicefeeamt: sbGlobal['servicefeeamt'],
			config: sbGlobal['config'],
			wt_seg_4: sbGlobal['wt_seg_4'],
			wt_mc_id: sbGlobal['wt_mc_id'],
			priceinfo: priceinfo,
			direct: sbGlobal['direct'],
			area: area,
			mode: sbGlobal['mode']
		},
		function(data) {
		
            // grid header start
            var gridHeader = $("table#grid-table thead tr");
            $.each(data.dates,function(i,row) {
                var th = $('<th></th>');
                if(travel == 'oneway') {
                    th.text(row);
                } else if(travel == 'roundtrip') {
					
					var br = $('<br/>');
					//var span1 = $('<span></span>');
					//var span2 = $('<span></span>');

					var text1 = row.fromDay+' - '+row.toDay
					//span1.text(text1);

//					var text2 = row.fromDate.substring(8,10);
					var text2 = row.fromDateNum;
					text2 += " "+row.fromMonthShort;
					text2 += " - ";
//					text2 += row.toDate.substring(8,10);
					text2 += row.toDateNum;
					text2 += " "+row.toMonthShort;
					//span2.text(text2);
					
					//th.append(span1);
					th.append(text1);
					th.append(br);
					th.append(text2);
					//th.append(span2);

					}
                gridHeader.append(th);
            });

            // grid header end
		
			// grid rows

			var j = 0;
			var minPrice = 0;
			var maxPrice = 0;
			var maxPriceText,minPriceText;
			$.each(data.destinations, function(i,row) {

				// intercont
				// only if one way
				interCont = 0;
				if(travel == 'oneway') {
					//if(i == 3) interCont = 1;
					if(row.intercont == 1) interCont = 1;
				}
				
				var somePrices = 0;
				$.each(row.days, function(n,day) {
					if(day.price) somePrices++;
				});
				
				if(somePrices || interCont) {				
										
					var tr = $('<tr></tr>');
					if(j == 0) {
						var th = $('<th></th>');
						th.addClass('to');
						th.text(lblTo);
						tr.append(th);
					}
					var dest = row.dest;
					var th = $('<th></th>');
					th.text(dest);
					th.addClass('dest');
					tr.append(th);	
				
					if(interCont) {
						var td = $('<td></td>');
						td.attr('colSpan',row.days.length);
						td.addClass('interCont');
						td.text($("div#intercont").text());
						tr.append(td);
						t.append(tr);
					
					} else {
						$.each(row.days, function(n,day) {
							var td = $('<td></td>');
							td.addClass('price');
						
							if(travel == 'roundtrip') {
								td.addClass('wide');
							}

							var divLeft = $('<div></div>');
							divLeft.addClass('left');

							var divPrice = $('<div></div>');
				
							divPrice.addClass('price');
						
							if(!day.price) td.addClass('empty');
							else {
								var a = $('<a></a>');
								a.attr('href',day.link);
								a.text(day.price);
								$(td,a).click(function() {
									//window.open(day.link);
									$("input[name=deeplink]").val(day.link);
									travellers('show');
									return false;
								});
								a.attr('onclick','return false;');
								divPrice.append(a);
							
								var price = day.price;
								price = price.replace(/[^\d]/g,'');
								price = parseInt(price);
								
								if(price < minPrice || !minPrice) {
									minPrice = price
									minPriceText = day.price
								}
								
								if(price > maxPrice || !maxPrice) {
									maxPriceText = day.price;
									maxPrice = price;
								}
							
								td.attr('rel',price);
							} 

							var divRight = $('<div></div>');
							divRight.addClass('right');
							
							td.append(divLeft);
							td.append(divPrice);
							td.append(divRight);
							tr.append(td);
							t.append(tr);
							
						});
					}
					j++;
					$('th.to').attr('rowspan',j);
				}
			});

            steps = sbGlobal['steps'];
		if( (maxPrice - minPrice) < 600) {
		steps = 10;
		}
			minPrice = (parseInt(Math.floor(minPrice/steps)-0))*steps;
			maxPrice = (parseInt(Math.ceil(maxPrice/steps))+0)*steps;
			$("div#minprice").text(minPrice);
			$("div#maxprice").text(maxPrice);
			$("div#selectedprice").text(maxPrice);
			
			$("#slider-price-bar").slider('option','min',minPrice);
			$("#slider-price-bar").slider('option','max',maxPrice);
			$("#slider-price-bar").slider('value',maxPrice);
			$("#slider-price-bar").slider('option','step',steps); 
			
			$("td.price").bind('mouseenter',function(e) {
				$(this).addClass('over');
			    
				var offset = $(this).offset();
				if(!$(this).hasClass('empty') && !$(this).hasClass('outofrange')) {
    				$("div#tooltip").css('top',offset.top+10)
    				               .css('left',offset.left+80)
    				               .show();
               }
               
				
			});	
			$("td.price").bind('mouseleave',function(e) {
				$(this).removeClass('over');
				$("div#msgbox").hide();
				$("div#tooltip").hide();
			});
			
			//$("div#grid").slideDown();
			$("div#footer-controls").show();
			$("table#grid-table").show();
			$("div#throbber").hide();
            gridLoading = 0;
			// enable controls
			$("div#selections input, div#selections select").attr('disabled',false);
			borderTop();
			
			// show msgbox
			var offset = $("td.price:first").offset();
			if(sbGlobal['mode'] == 'big5') {
				offsetX = 160;
				offsetY = 4;
			} else {
				offsetX = 108;
				offsetY = 4;
			}
			
			$("div#msgbox").css('top',offset.top-offsetY)
			               .css('left',offset.left-offsetX)
			               .show();

	    }
    );
}

function borderTop() {
	// top right
	var tr = $("table#border-top");
	var newWidth = parseInt($("div#grid").width())-parseInt($("table#grid-table").width());
	if(newWidth > 0) {
    	tr.css('width',newWidth+'px');
	    var newHeight = parseInt($("table#grid-table th.selectprice").height());
    	if($.browser.mozilla) {
    		newHeight += 3;
    	}
    	tr.find('th').css('height',newHeight);
    	tr.show();
	}
}

function slidePrice() {
	var t = $("div#selectedprice");
	var price = $("div#slider-price-bar").slider('value');
	
	// put value in slider handle
	$(".ui-slider-handle").text(price);
	
	t.text(price);
	$("tbody#gridcontent td.price").each(function() {
		if(parseInt($(this).attr('rel')) > price) {
			$(this).addClass('outofrange');
		} else {
			$(this).removeClass('outofrange');
		}
	});	
};

function populateOrg() {

	// previously selected
	selOrg = $("form#tripForm select[name=org] option:selected").val();
	if(selOrg) {
		sbGlobal['org'] = selOrg;
	}

	// empty org
	var t = $("select[name=org]");
	t.empty();
	// add empty
	var option = $("<option></option>");
	option.text('-');
	option.val('');
	t.append(option);
	
	var pos = sbGlobal['pos'];
	var lng = sbGlobal['lng'];
	var org = sbGlobal['org'];
	
    $.getJSON('org.php',
        {
            pos:pos,
            lng:lng,
            config: sbGlobal['config'],
            direct: sbGlobal['direct'],
			mode: sbGlobal['mode']
        },function(data) {
        $.each(data, function(i,o) {
            var option = $("<option></option>");
            option.val(o.org);
            option.text(o.name);
            if(org) {
                if(org == o.org) {
                    option.attr('selected','selected');
                }
            }
            t.append(option);
        });
		loadCalendar();
		loadGrid(sbGlobal['week'],sbGlobal['month']);
    });
}

function populateDays(change) {

	// selected outday
	var outday = $("select[name=outday] option:selected").val();

	// previously selected
	if(change) {
		sbGlobal['days'] = parseInt($("select[name=days] option:selected").val());
		var diff = sbGlobal['outday']-outday;
		diff = parseInt(diff);
		sbGlobal['days'] += diff
		
		//alert(outday+"\n"+sbGlobal['outday']+'\n'+diff+'\n'+sbGlobal['days']);
	}

	// empty org
	var t = $("select[name=days]");
	t.empty();
	// add empty
	var option = $("<option></option>");
	option.text('-');
	option.val('');
	t.append(option);

	var pos = sbGlobal['pos'];
	var lng = sbGlobal['lng'];

	var days = sbGlobal['days'];	
	// remember
	sbGlobal['outday'] = outday;
	
	var org = $("select[name=org] option:selected").val();
	
    if(outday) {
        $.getJSON('json_sel_ret.php',
            {
                pos:pos,
                lng: sbGlobal['lng'],
                outday:outday,
                org:org,
                config: sbGlobal['config'],
                direct: sbGlobal['direct'],
				mode: sbGlobal['mode']
            },function(data) {
            $.each(data, function(i,o) {
                var option = $("<option></option>");
                option.val(o.value);
                option.text(o.text);
                if((days && days == o.value) || (days == undefined && o.value == sbGlobal['days'])) {
                    option.attr('selected','selected');
                }
                t.append(option);
            });
		    loadGrid();
        });
    }
}

function destinationSelector(action) {
	if(action == 'show') {
		$("#msgbox").hide();
		destinationLoad();
		$(document).scrollTop(0);
		$("#wrapper-grid").slideUp(function() {
			// disable controls
			//$("div#selections input, div#selections select").attr('disabled','disabled');
			$("div#selections").hide();
			$("#footer-top").hide();
			$("#destinations").slideDown();
		});
	} else {
		destinationsSave();
		$("#destinations").slideUp(function() {
			$("#footer-top").show();
			$("#wrapper-grid").slideDown();
			$("div#selections").show();
		});
	}
}

function destinationLoad() {
	var t = $("div#destination-list");
	t.empty();
	$("div#destination-throbber").show();
	var url = "json_sb_destinations.php";
	$.getJSON(url,
	    {
	        pos:sbGlobal['pos'],
	        lng: sbGlobal['lng'],
	        config: sbGlobal['config'],
	        direct: sbGlobal['direct'],
			mode: sbGlobal['mode']
        },function(data) {
		var ul = new Array();
		var citiescount = 0;
		var totalcount = 0;
		$.each(data.cats,function(i,d) {
			totalcount++;
			$.each(data.cats[i].Cities,function(j,city) {
				totalcount++;
			});
		});
		var cols = new Array(5);
		$.each(cols,function(i,col) {
			cols[i] = $("<div></div>");
			cols[i].addClass('col');
		});
		var colCount = parseInt(totalcount/cols.length);
		var rows = new Array(totalcount);
		var j = 0;
		var currentCol = 0;
		$.each(data.cats,function(i,d) {
			var input1 = $('<input/>');
			input1.attr('type','checkbox');
			input1.attr('name','country');
			input1.val(d.CountryCode);
		
			input1.click(function() {
				var checked = false;
				if($(this).is(':checked')) {
					checked = true;
				}
				var findClass = $(this).val();
				$('div#destination-list input').each(function() {
					if($(this).hasClass(findClass)) {
						$(this).attr('checked',checked);
					}
				});
			});
			
			if(j > 0) {
				cols[currentCol].append($("<br/>"));			
			}
			cols[currentCol].append(input1);
			cols[currentCol].append($("<b>"+d.CountryName+"</b>"));			
			cols[currentCol].append($("<br/>"));			
			if(j >= colCount) {
				j = 0;
				t.append(cols[currentCol]);
				currentCol++;
			} else j++;
			$.each(data.cats[i].Cities,function(n,city) {
				var input = $('<input/>');
				input.addClass(data.cats[i].CountryCode)
				input.attr('type','checkbox');
				input.attr('name','city[]');
				input.val(data.cats[i].Cities[n].CityCode);
				//if(!data.favs.length && data.cats[i].Cities[n].Properties['buffetdest']) {
				//	input.attr('checked','checked');
				//	alert(input.attr('checked'));
				//}
				cols[currentCol].append(input);
				cols[currentCol].append(data.cats[i].Cities[n].CityName);
				cols[currentCol].append($("<br/>"));			
				if(j >= colCount) {
					j = 0;
					t.append(cols[currentCol]);
					currentCol++;
				} else j++;
			});
		});
		
		if(!data.favs.length) {
		    $("input[value=buffetdest]").attr('checked','checked').each(destinationsCategory);
		}
		$("div#destination-list input").click(function() {
		    $("fieldset[name=categories] input").attr('checked',false);
		});
		
		t.append(cols[currentCol]);

		$.each(data.favs,function(i,f) {
			$("input[value="+f+"]").attr('checked',true);
		});

		$("div#destination-throbber").hide();

	});
}

function destinationsCategory() {

	$("div#destinations input").attr('disabled','disabled');

	var checked = false;
	var cat = $(this).val();
	if($(this).is(':checked')) {
		checked = true;
	}
	var url = "json_sb_destinations.php";
	$.getJSON(url,
	    {
	        pos:sbGlobal['pos'],
	        lng: sbGlobal['lng'],
	        config: sbGlobal['config'],
	        direct: sbGlobal['direct'],
			mode: sbGlobal['mode']
        },function(data) {
		var str = '';
		$.each(data.cats,function(i,d) {
			$.each(d.Cities,function(j,city) {
				if(city.Properties[cat]) {
					$('div#destination-list input[value='+d.Cities[j].CityCode+']').attr('checked',checked);
				}
			});
		});
		$("div#destinations input").attr('disabled',false);

	});
}

function destinationsClearAll() {
	$('div#destinations input[type=checkbox]:checked').attr('checked',false);
}

function destinationsSave() {
    var url = 'json_sb_dest_save.php';
    var input = $("<input/>");
    input.attr('name','config');
    input.val(sbGlobal['config']);
    input.attr('type','checkbox');
    input.attr('checked','checked');
    $('form#destinationsForm').append(input);
	$.get(url,$('form#destinationsForm input:checked').serialize(),function(data) {
	    loadGrid(false,false,1);
    });
}

function destinationsStickySave() {
    var url = 'json_sb_sticky_save.php';
	$.get(url,
	    {
	        pos:sbGlobal['pos'],
            config: sbGlobal['config'],
            direct: sbGlobal['direct']
        },function(data) {
	    //loadGrid(false,false,1);
    });
}

function travellers(action) {
	if(action == 'hide') {
		$("div#travellers, div#big-transparent").hide();
		$("input[name=deeplink]").val('');
	} else {
	    // check eurobonus
	    var priceinfo = $("form#tripForm input[name=priceinfo]:checked").val();
	    if(priceinfo == 'eurobonus') {
            eurobonusHandler('check');
        } else {
	        $("#eurobonusLogin").hide();
        }
		$("div#big-transparent").height($(document).height());
		$("div#big-transparent").width($(document).width());
		$("div#travellers").css('top',$(document).scrollTop()+200);
		
		$("div#travellers, div#big-transparent").show();
	}
}

function deepLink(goDeeper) {

    // eurobonus, validate login
    var priceinfo = $("form#tripForm input[name=priceinfo]:checked").val();
    if(priceinfo == 'eurobonus' && goDeeper == undefined && $("#eurobonusLogin").css('display') == 'block') {
        eurobonusHandler('login');
        //alert("aborted deeplink");
        // abort and wait for result
        return false;
    }

	var link = $("input[name=deeplink]").val();
	var adt = $("select[name=adults] option:selected").val();
	var chd = $("select[name=children] option:selected").val();
	var inf = $("select[name=infants] option:selected").val();
	
	var a = link.split('?');
	var base = a[0];
	var qStr = a[1];
	var a = qStr.split('&');
	var qs = '';
	for(var i=0;i<a.length;i++) {
		var index = a[i].indexOf('=');
		var key = a[i].substring(0,index);
		var val = a[i].substring(index+1);        
		if(key == 'adt' || key == 'adults') {
			val = adt;
		} else if (key == 'chd_2-11' || key == 'children') {
			val = chd;
		} else if(key == 'inf' || key == 'infants') {
			val = inf;
		}
		qs +=  key+"="+val+"&";
	}

	link = base+"?"+qs;
	
	//window.open(link);
	top.location.href=link;

}

function trReplace(priceinfo) {

	if(priceinfo == undefined) priceinfo = $("form#tripForm input[name=priceinfo]:checked").val();

	if(priceinfo == 'eurobonus') {
	    sbGlobal['config'] = 99;
	    $("form#tripForm select[name=travel]").val('roundtrip');
    } else sbGlobal['config'] = 0;

	// reload org/dest
	populateOrg();
	
	$.getJSON('json_tr.php',
		{	
			pos: sbGlobal['pos'],
			config: sbGlobal['config'],
			lng: sbGlobal['lng'],
			direct: sbGlobal['direct'],
			mode: sbGlobal['mode']
		},
		function(data) {
			$.each(data,function(key,val) {
				if(key) {
					var c = $("."+key);
					if(c.hasClass('cufonTitle')) {
						c.empty().text(val);
						Cufon.replace(c);
					} else c.text(val);
				}
			});
		}
	);
	
}

// eurobonus
function eurobonusHandler(cmd) {
    var url = 'http://link.flysas.net/eurobonus/isLoggedIn.php?';
    var url = 'http://gui.flysas.net/eurobonus/isLoggedIn.php?';
    //var url = '/eurobonus/isLoggedIn.php?';
    //var url = 'login.html?';
    var t = $("#eurobonushandler");
	$("#eurobonusLoginError").hide();
    t.empty();
    var qstr;
    var status;
    if(cmd == 'check') {
        var params = {
            action: 'check',
            pos: sbGlobal['pos']
        };
        qstr = $.param(params);
        t.attr('src',url+qstr)  
         .load(function() {
            status = t.contents().find('#sso_responce').text();
            status = trimStr(status);
            //alert(status);
            if(status) {
                //alert('eurbobonusHandlers check status:\n|'+status+'|');
                if(status == 'OK') {
        	        $("#eurobonusLogin").hide();
    	        } else {
        	        $("#eurobonusLogin").show();
    	        }
            }
        });
    }  else if(cmd == 'login') {

        // unbind button
		$("#eurobonusLoginThrobber").show();
        $("#deeplink").unbind().find('.label').css('color','#aaa'); 
        $("#eurobonusLoginError").hide().find('p').text(''); 
        
        var params = {
            action: 'login',
            uid: $("input[name=uid]").val(),
            pwd: $("input[name=pwd]").val(),
            pos: sbGlobal['pos']
        };
        qstr = $.param(params);

        t.attr('src',url+qstr).load(function() {
            status = t.contents().find('#sso_responce').text();
            status = trimStr(status);
            //alert('EBHANDLER:\n'+t.contents().find('#sso_responce').length+'\n'+status);
            if(status && t.contents().find('#sso_responce').length) {
                if(status == 'OK') {
                    $("#eurobonusLoginError").show().find('p').text('Login Ok');
                    deepLink(1);
                } else if(status != 'NULL') {
                    $("#eurobonusLoginError").show().find('p').text(status);
                    // enable booking button
					$("#eurobonusLoginThrobber").hide();
                    $("div#deeplink").click(function() {
                        deepLink()
                    }).find('.label').css('color','#fff')
                } else {
					$("#eurobonusLoginError").hide();
				}
            }
        });
    }

}

function trimStr(str) {
    str = str.toString();
    str = str.replace(/^[\s\n\r\t]+/g,"");
    str = str.replace(/[\s\n\r\t]+$/g,"");
    return str;
}

