Date.patterns = {
    ISO8601Long:"Y-m-d H:i:s",
    ISO8601Short:"Y-m-d",
    ShortDate: "n/j/Y",
    LongDate: "l, F d, Y",
    FullDateTime: "l, F d, Y g:i:s A",
    MonthDay: "F d",
    ShortTime: "g:i A",
    LongTime: "g:i:s A",
    SortableDateTime: "Y-m-d\\TH:i:s",
    UniversalSortableDateTime: "Y-m-d H:i:sO",
    YearMonth: "F, Y"
};

Ext.form.VTypes["postalcodeVal"] = /^([a-zA-Z][0-9]){3}$/;
Ext.form.VTypes["postalcode"]=function(v){
 	Ext.form.VTypes["postalcodeText"] = "Postal codes are always formatted in the same sequence: alphabetic character / numeral / alpha /numeral / alpha / numeral (e.g. K1A0B1).";
 	return Ext.form.VTypes["postalcodeVal"].test(v);
}

Ext.form.VTypes["wordverificationVal"] = /[a-zA-Z0-9]{6,6}$/;
Ext.form.VTypes["wordverification"]=function(v){
 	return Ext.form.VTypes["wordverificationVal"].test(v);
}

Ext.form.VTypes["usernameVal1"] =  /^.{6,30}$/;
Ext.form.VTypes["usernameVal2"] = /[-_.a-zA-Z0-9]{6,30}$/;
Ext.form.VTypes["username"]=function(v){
	if(!Ext.form.VTypes["usernameVal1"].test(v)){		
  		Ext.form.VTypes["usernameText"] = 'Username length must be 6 to 31 characters long';
  		return false;
 	}
 	
 	Ext.form.VTypes["usernameText"] = 'Username must only contain letters, numbers, hyphen, underscore or a period.';
 	return Ext.form.VTypes["usernameVal2"].test(v);
}

Ext.form.VTypes["passwordVal1"] = /^.{6,31}$/;
Ext.form.VTypes["passwordVal2"] = /[^a-zA-Z].*[^a-zA-Z]/;
Ext.form.VTypes["password"]=function(v){
	if(!Ext.form.VTypes["passwordVal1"].test(v)){		
  		Ext.form.VTypes["passwordText"] = "Password length must be 6 to 31 characters long";
  		return false;
 	}
 	
 	Ext.form.VTypes["passwordText"] = "Password must include at least 2 numbers or symbols";
 	return Ext.form.VTypes["passwordVal2"].test(v);
}

Ext.form.VTypes["passwordText"] = "Invalid Password";
Ext.form.VTypes["passwordMask"] = /./;

//display hidden forms
Ext.override(Ext.form.BasicForm, {
    initEl : function(el){
        this.el = Ext.get(el);
        this.id = this.el.dom.getAttribute("id") || Ext.id();
        this.el.on('submit', this.onSubmit, this);
        this.el.addClass('x-form');
    },
    
    highlightInvalid: function() {
    	Ext.fly(Ext.DomQuery.select("#" + this.id + f.invalidClass)).frame("red");
    },

    areFieldsValid: function() {
        var valid = true;
        this.items.each(function(f){
            if(f.el.hasClass(f.invalidClass)){
                valid = false;
            }
            return valid; // Abort iteration at first invalid Field! 
        });
        return valid;
    }
});

Ext.form.HiddenField = function(config){
    config.type = 'hidden';
    config.inputType = 'hidden';
    Ext.form.HiddenField.superclass.constructor.call(this, config);
};

Ext.extend(Ext.form.HiddenField, Ext.form.TextField,  {
    onRender : function(ct, position){
        if(this.el){
            this.el = Ext.get(this.el);
            if(!this.target){
                ct.dom.appendChild(this.el.dom);
            }
        }else {
            var cfg = {tag: "input", type: "hidden"};
            if(!cfg.name){
                cfg.name = this.name || this.id;
            }
            this.el = ct.createChild(cfg, position);
        }
        this.el.dom.readOnly = true;
        this.el.dom.parentNode.parentNode.style.display = 'none';
        this.initValue();
    }
});

Ext.util.GoogleMaps = {
	postalCodeLatitude : '',
	postalCodeLongitude : '',
	postalCode : '',
	
	getPostalCode: function(){
		return this.postalCode.toString();
	},
	
	setPostalCode: function(value){
		this.postalCode = value;
	},
	
	getPostalCodeLatitude: function(){
		return this.postalCodeLatitude.toString();
	},
	
	setPostalCodeLatitude: function(value){
		this.postalCodeLatitude = value;
	},
	
	getPostalCodeLongitude: function(){
		return this.postalCodeLongitude.toString();
	},
	
	setPostalCodeLongitude: function(value){
		this.postalCodeLongitude = value;
	},
	
	isAvailable: function(){
		if(typeof GIcon == "undefined"){
    		return false;
		} else {
			return true;
		}
	},
	
	createMap: function(tab, div, ds, colour, latitude, longitude){
		var mapTabDiv = tab;
		var mapDiv = div;
		mapDiv.style.height = mapTabDiv.getComputedHeight();
		mapDiv.style.width = mapTabDiv.getComputedWidth();
		
		var nearbyIcon = new google.maps.Icon();		
		nearbyIcon.shadow = "images/mm_20_shadow.png";
		nearbyIcon.iconSize = new google.maps.Size(12, 20);
		nearbyIcon.shadowSize = new google.maps.Size(22, 20);
		nearbyIcon.iconAnchor = new google.maps.Point(6, 20);
		nearbyIcon.infoWindowAnchor = new google.maps.Point(5, 1);
		
		
		var map = new google.maps.Map2(mapDiv);		
		map.addControl(new google.maps.LargeMapControl());
		map.addControl(new google.maps.ScaleControl());
		map.addControl(new google.maps.MapTypeControl());
		map.addControl(new DragZoomControl(
            {
                opacity:.2,
                border:"2px solid red"
            },{
                buttonHTML:"<img src='/images/zoom-button.gif' />",
                buttonZoomingHTML:"<img src='/images/zoom-button-activated.gif' />",
                buttonStartingStyle:{width:'24px',height:'24px'}
            }
           )
        );	
		
		var firstPoint = true;
		
		if (ds.getCount() > 0){
			for (var i=0; i<ds.getCount(); i++){
				record = ds.getAt(i);
				
				if (record.get("latitude") != 0 && record.get("longitude") != 0){
					var point = new google.maps.LatLng(record.get("latitude"), record.get("longitude"));
					if (firstPoint == true){
						map.setCenter(point, 10);
						firstPoint = false;	
					}
					
					if (record.get("type") == 'c'){
						nearbyIcon.image = "images/marker_20_red.png";
					}
					
					switch(record.get("type")) {
						case 'r':
							nearbyIcon.image = "images/marker_20_brown.png";
							break
						case 'w':
							nearbyIcon.image = "images/marker_20_orange.png";
							break  
						default:
							nearbyIcon.image = "images/marker_20_red.png";
					}
					
					var marker = this.createMarker(point, this.displayRestaurantHtml(record), nearbyIcon);
					map.addOverlay(marker);	
				}			
			}
		
			ds.sort("latitude");
			var y1 = ds.getAt(0).get("latitude");
			var y2 = ds.getAt(ds.getCount()-1).get("latitude");
			
			ds.sort("longitude");
			var x1 = ds.getAt(0).get("longitude");
			var x2 = ds.getAt(ds.getCount()-1).get("longitude");
			
			var sw = new google.maps.LatLng(y1, x1);
			var ne = new google.maps.LatLng(y2, x2);
			
			var bounds = new google.maps.LatLngBounds(sw, ne);
			map.panTo(bounds.getCenter());
			map.setZoom(map.getBoundsZoomLevel(bounds));
			
			if (this.getPostalCodeLatitude().length > 0 && this.getPostalCodeLongitude().length > 0){
				var point = new google.maps.LatLng(this.postalCodeLatitude, this.postalCodeLongitude);
				map.panTo(point);
				
				var postalCodeIcon = new google.maps.Icon();
				postalCodeIcon.image = "images/marker_34_red.png";
				postalCodeIcon.shadow = "images/shadow50.png";
				postalCodeIcon.iconSize = new google.maps.Size(20, 34);
				postalCodeIcon.shadowSize = new google.maps.Size(37, 34);
				postalCodeIcon.iconAnchor = new google.maps.Point(9, 34);
				postalCodeIcon.infoWindowAnchor = new google.maps.Point(9, 2);
				postalCodeIcon.infoShadowAnchor = new google.maps.Point(18, 25);
				
				var html = "<h4>" + this.getPostalCode() + "</h4>";
				var postalCodeMarker = this.createMarker(point, html, postalCodeIcon);
				map.addOverlay(postalCodeMarker);
				postalCodeMarker.openInfoWindowHtml(html);
			}
			
		} else {
			var point = new google.maps.LatLng(45.413153, -75.678978);
			map.setCenter(point, 12);
		}
		
		return map;
	},
	
	createMarker: function (point, value, icon) {
	  var marker = new google.maps.Marker(point, icon);
	  GEvent.addListener(marker, "mouseover", function() {
	    marker.openInfoWindowHtml(value);
	  });		  
	  return marker;
	},
	
	displayRestaurantHtml: function(record){
		var html = "<h4>" + String.format('<a href="/restaurant/{0}/">{1}</a>', record.get("restaurant_id"), record.get("restaurant_name")) + "</h4>";
		html += record.get("address") + "<br />";
		html += record.get("city") + ", " +  record.get("province") + "&nbsp;" + record.get("postal_code") + "<br />";
		
		if (record.get("telephone").indexOf(")") > 0){
			html += record.get("telephone") + "<br />";
		} else {
			html += '(' + record.get("telephone").substring(0,3) + ') ' + record.get("telephone").substring(3,6) + '-' + record.get("telephone").substring(6,10);
		}
		
		if (record.get("average_rating") > 0){
			html +=  "<br /><br />" + this.renderRating(record.get("average_rating"));
		} else if (record.get("rating") > 0){
			html +=  "<br />" + this.renderRating(record.get("rating"));
		}
		
		return html;
	},
	
	renderRating: function(value){
		var fullStars = "";
		var emptyStars = "";			
		
		for (var i=0; i<value; i++){
			fullStars = fullStars + "*";
		}
		
		for (var i=0; i<(5-value); i++){
			emptyStars = emptyStars + "*";
		}
		
		return '<font class="ratings" color="#cc3300">' + fullStars + '</font><font class="ratings" color="#cccccc">' + emptyStars + '</font>';
	}
};

Ext.onReady(function(){
	var ccc = Ext.get('ccc');
	
	if (ccc != null){
		ccc.on('click', function(e){
	        Ext.MessageBox.show({
	           title: 'Hungy Table',
	           msg: "Do you have a comment, complaint or compliment? We're always looking for feedback to improve this site.",
	           width:400,          
	           buttons: Ext.MessageBox.OKCANCEL,
	           multiline: 150,
	           fn: sendMessage,
	           animEl: 'ccc',
	           cls: 'msgBoxCss'
	       });
	    });
	    
		function sendMessage(btn, text){
	    	if (btn == 'ok'){
	    		var message = text;
	    		
	        	Ext.Ajax.request({
					url: 'xhr.php',
					params: 'action=mail&type=comment&body=' + text,
					method: 'POST'
	    		});
	    	}
	    };
	}
});

function unloadGMap(){
    try {
        GUnload();
    } catch(err) {
        var a = err;
    }
}