(function ($) {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        s = {
            'array': function (x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function (x) {
                return String(x);
            },
            'null': function (x) {
                return "null";
            },
            'number': function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            'object': function (x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        v = x[i];
                        f = s[typeof v];
                        if (f) {
                            v = f(v);
                            if (typeof v == 'string') {
                                if (b) {
                                    a[a.length] = ',';
                                }
                                a.push(s.string(i), ':', v);
                                b = true;
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            'string': function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };

	$.toJSON = function(v) {
		var f = isNaN(v) ? s[typeof v] : s['number'];
		if (f) return f(v);
	};

	$.parseJSON = function(v, safe) {
		if (safe === undefined) safe = $.parseJSON.safe;
		if (safe && !/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(v))
			return undefined;
		return eval('('+v+')');
	};

	$.parseJSON.safe = false;

})(jQuery);

$.fn.delay = function(time, name) {
    return this.queue((name || 'fx'), function() {
        var self = this;
        setTimeout(function() { $.dequeue(self); } , time);
    });
};

function loadSlideShow(groupID) {
	$('a.slideshow-' + groupID).colorbox({
		slideshow: true,
		transition: 'elastic'
	});
}


function SearchSwitcher(type) {
	quickSearch.hideAll();
	
	switch (type) {
		case "FlightHotel":
		    quickSearch.showItem('select_flight');
			quickSearch.setUrls('Flights|Hotels|Passengers|Services|Payment|Receipt');
			quickSearch.searchType = 'Departures';
			break;
		case "FlightOnly":
		    quickSearch.showItem('select_flight');
			quickSearch.setUrls('Flights|Passengers|Payment|Receipt');
			quickSearch.searchType = 'Departures';
			break;
		case "Packages":
		    quickSearch.showItem('select_package');
			quickSearch.searchType = 'Packages';
			quickSearch.setUrls('Package|Passengers|Payment|Receipt');
			break;
	}
}
function GoToCategory(element) {
	top.window.location.href = "/" + $(element).attr('category') + "/";
}
function SetDefaultRadio(cat) {
	$("input[category=" + cat + "]").attr("checked","checked");
}

function SetQuickSearchColor(cat) {
	if (cat === "") {
		type = "FlightOnly";
		quickSearch.freezeElements = true;
		setTimeout('DisableDropDowns()', 500);
		//DisableDropDowns();
		
	} else {
		type = $("input[category=" + cat + "]").val();
	}
	$('#boka').addClass('theme-' + cat);
	
	SetDefaultRadio(cat);
	SearchSwitcher(type);
	
	if (type == "Packages") {
	    defaultId = $(".qs_search_type_packages[category=" + cat + "]").attr("defaultPackageCategory");
		if (defaultId > 0) {
			$("#qs_packagecategory_id > option[value=" + defaultId + "]").attr('selected','selected');
			quickSearch.loadPackages(defaultId);
		}
	}  
}

function DisableDropDowns() {
	$('#select_flight > .item > select , #qs_adult_count,#qs_child_count,#qs_infant_count, ').each(function(i, item) {
		$(item).attr('disabled','true');
		$(item).empty();
		$(item).html('<option>--</option>');
		$(item).addClass('form-element-disabled');
	});
	
	$('#Continue').attr('onclick', '').click( function(){alert('Vinsamlegast veldu ferð.');} );
}    

function SetDefaultQuickSearch(url) {
	$('#boka').removeClass();
	SetQuickSearchColor(url);  
	var c = $.cookieJar('ODIN-BOOKING-DATA-UU', {
			expires: 7,
			path: '/',
			cookiePrefix: ''
	});	
	source = c.set('source', url);   
}

function SetCookieQuickSearch() {
	var c = $.cookieJar('ODIN-BOOKING-DATA-UU', {
			expires: 7,
			path: '/',
			cookiePrefix: ''
	});	
	source = c.get('source');  
	SetQuickSearchColor(source);
}

HotelSelection = function() {
	this.init();
}

HotelImageMovers = function() {
  this.init();
};

	/*	HAFÐU SAMBAND:
	--------------------------------------------------------------------------------------------------------------------- */
SendEmail = function(btn, subject, to) {
  this.init(btn, subject, to);
};
jQuery.extend(SendEmail.prototype, {
	init: function(btn, subject, to) {
		var qs = 'i_subject=' + subject + '&i_to=' + to;	
		var items = $('input.email-form-item,select.email-form-item,textarea.email-form-item').each(
			function(i, el) {
				qs += '&' + $(el).attr('id') + '=' + $(el).val();
			}
		);
		$.post('/Modules/Forms/Submit.aspx', qs, function(r) {
			if(r) {
				alert('Skilaboð hafa verið send'); 
				$('Nafn').value = ''; 
				$('Netfang').value = '';
				$('Fyrirspurn').value = '';
			} else {
				alert('Ekki tokst að senda skilabod');
			}   
			btn.disabled = false;
			btn.value = 'Senda';	
		});
	}
});


function verifycontactform(btn) {
	btn.disabled = true;
	btn.value = 'Sendi skilabod ...';
	var message = "Vinsamlegast fylltu ut: ";
	var isGood = true;
	var emailRegEx = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
	
	if ( $('#Netfang').val() == "") {
		message = message + "\n -  Netfang";
		isGood = false;
	}
	if ( $('#Fyrirspurn').val() == "") {
		message = message + "\n -  Fyrirspurn";
		isGood = false;
	}
	if (!$('#Netfang').val().match(emailRegEx) ) {
		message = message + "\n -  Fyrirspurn";
		isGood = false;
	}
	
	if (isGood) {
		new SendEmail(btn, 'Hafa samband - skilabod af uu.is', 'info@uu.is');
	} else {
		alert(message);
		btn.disabled = false;
		btn.value = 'Senda';
	}

	return isGood;
}

	/*	GOOGLE MAPS - FIND HOTELS:
	--------------------------------------------------------------------------------------------------------------------- */    
function Hotel (id, name, lng, lat, imagepath, stars, minprice){
  this.id = id;
  this.name = name;
  this.lng = lng;
  this.lat = lat;
  this.imagepath = imagepath;
  this.stars = stars;        
  this.minprice = minprice;       
  this.GLatLng = new GLatLng(lat, lng);
}

function Location(id, name, lng, lat, icon, typename) {
  this.id = id;
  this.name = name;
  this.long = lng;
  this.lat = lat;
  this.icon = icon;
  this.typename = typename;      
  
  this.GLatLng = new GLatLng(lat, lng);
}

GMapFindHotels = function(element, ownerInfo) {
  this.init(element, ownerInfo);
};
jQuery.extend(GMapFindHotels.prototype, {	                               
  init: function(element, ownerInfo){                                                
		this.hotels = new Array();
    this.locations = new Array();
    this.map = null; 
    this.mgr = null;       
    this.total_lat = 0; 
    this.total_lng = 0;  
    this.element = element;
    this.ownerInfo = ownerInfo;
    
		this.currentLocations = null;
		this.currentHotel = null;
		this.bounds = new GLatLngBounds();
	},
  
  InitMap: function( ) {  
  		if( this.map === null ) {
	      var defaultIcon = new GIcon(G_DEFAULT_ICON);
	      defaultIcon.image = "http://google-maps-icons.googlecode.com/files/hotel.png";
	      defaultIcon.iconAnchor = new GPoint(14,28);    
	      defaultIcon.iconSize = new GSize(28, 28);
	      
	      var center = new GLatLng(this.total_lat / this.hotels.length, this.total_lng / this.hotels.length);
	                                                                       
	      this.map = new GMap2(document.getElementById(this.element));
	      //map.enableGoogleBar();
	      this.map.addControl(new GLargeMapControl3D()); 
	      this.map.addControl(new GOverviewMapControl());
	      this.map.addControl(new GHierarchicalMapTypeControl());
	      //map.addControl(new GNavLabelControl(), new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(10,10) ) );
	      //map.enableScrollWheelZoom();            
	      //this.map.addMapType(G_SATELLITE_3D_MAP);
	      this.map.setCenter( this.bounds.getCenter(), this.map.getBoundsZoomLevel(this.bounds) -1 );
	      
	      var mgrOptions = { borderPadding: 50, maxZoom: 25, trackMarkers: false };
	      this.mgr = new MarkerManager(this.map, mgrOptions);
	      
	      // Add the hotel markers
	      for( var i = 0; i < this.hotels.length; i++) {
	        tmpMarker = new GMarker( this.hotels[i].GLatLng, {icon:defaultIcon});   	        
	        GEvent.addListener(tmpMarker, 'click', this.mouseOverHotel);
					this.mgr.addMarker( tmpMarker, 0, 25); 
	      }         
	             
	      // Add the location markers
	      for( var i = 0; i < this.locations.length; i++) {
	        icon = new GIcon(defaultIcon, this.locations[i].icon);
	        tmpMarker = new GMarker( this.locations[i].GLatLng, {icon:icon});
	        tmpMarker.image = this.locations[i].icon;    
	        GEvent.addListener(tmpMarker, 'click', this.mouseOverLocation);
	        this.mgr.addMarker( tmpMarker, 0, 25);
	      }                   
	      
	      this.mgr.refresh();
	      
	      window.onbeforeunload = GUnload;
	    }
  },
  
  addHotel: function(id, name, lng, lat, imagepath, stars, minprice) {
		this.hotels.push(new Hotel(id, name, lng, lat, imagepath, stars, minprice ));
		this.total_lat += parseFloat(lat);
		this.total_lng += parseFloat(lng);
		
		this.bounds.extend(new GLatLng(lat, lng));
	},
	
	addLocation: function(id, name, lng, lat, icon, typename){
		this.locations.push( new Location(id, name, lng, lat, icon, typename) );
		
		this.bounds.extend(new GLatLng(lat, lng));	
	},
  
  getHotelByLatLng: function(LatLng) {
    for(var i = 0; i < this.hotels.length; i++ ) {
      if( this.hotels[i].GLatLng === LatLng )
        return this.hotels[i];
    } 
  },
  
  getLocationByLatLng: function(LatLng) {
    for(var i = 0; i < this.locations.length; i++ ) {
      if( this.locations[i].GLatLng === LatLng )
        return this.locations[i];
    }
  },
  
  mouseOverHotel: function(LatLngPos){
    var hotel = __gmap.getHotelByLatLng(LatLngPos);
    __gmap.currentHotel = hotel;
    
    __gmap.map.openInfoWindowTabsHtml(
				LatLngPos, [
					new GInfoWindowTab( 'Info', $('#hotel_info_' + hotel.id).html()),
					new GInfoWindowTab( 'Attractions', '<div id="hotel_info_locations"><img src="/templates/common/images/image-loader.gif" /></div>') 
		], {
				maxContent: '<div class="hotel_info">' + $('#hotel_item_' + hotel.id).html() + '</div>',
				maxTitle: '<div class="hotel_title">' + hotel.name + ' <span class="einkunn stars' + hotel.stars + '"> </span></div>',
				onCloseFn: function(){ if(__gmap.polyline != null){__gmap.map.removeOverlay(__gmap.polyline); __gmap.polyline = null; }}
		});
    __gmap.map.getInfoWindow().enableMaximize();
    
    setTimeout('__gmap.refreshLocations('+hotel.id+')', 200);
  }, 
	
	refreshLocations: function(hotelID){          
    Zeus.Odin.DisillModules.API.OdinAPI.HotelLocations( __gmap.ownerInfo, hotelID, function(r) {
				div = [];
				while(div.length == 0) div = $('#hotel_info_locations');
				div.html('');
				__gmap.currentLocations = r;
				for(var i = 0; i < Math.min(r.length, 9); i++){
					lng = r[i].Coordinates.Longitude;
					lat = r[i].Coordinates.Latitude;
					div.append('<div class="attraction"><span class="location_name">' + r[i].Name + '</span><span class="show_line" onclick="__gmap.mouseOverLocationDistance(' + i + ');">(show)</span><span class="distance">' + double2str(r[i].Distance) + ' km.</span></div>');
				}			
				
			}, Error);
	},                                        
  
  mouseOverLocation: function(LatLngPos){
    var location = __gmap.getLocationByLatLng(LatLngPos);
    if(location != null) {
	    __gmap.map.openInfoWindowHtml(LatLngPos, $('#location_desc_' + location.id).html() );        
	    __gmap.map.getInfoWindow().disableMaximize();
	  }
  },
	
	mouseOverLocationDistance: function(index) {
		if(__gmap.polyline != null) {
			__gmap.map.removeOverlay(__gmap.polyline);
		}
		pt = new GLatLng( __gmap.currentLocations[index].Coordinates.Latitude, __gmap.currentLocations[index].Coordinates.Longitude );
		this.polyline = new GPolyline([
		  __gmap.currentHotel.GLatLng, pt
		], '#0000ff', 5);
		__gmap.map.addOverlay(__gmap.polyline);	
	}    
});

var __gmap = null;

function NewGMap(element, ownerInfo) {
	__gmap = new GMapFindHotels(element, ownerInfo);
	return __gmap;
}

function double2str(X) {
    with (new Object(Math.round(100 * X) + "")) {
        return substring(0, length - 2) + "," + substring(length - 2, length);
    }
}  