// Base website URL
var baseUrl     = 'www.arroyogrande.org';
var scrollState = true;
/**
 * Fix background-image flicker problem in IE 6
 */
try {
	document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}
/**
 * Sets up global error handling for AJAX requests
 * 
 * @return		void
 */
function setupAjax() {
	var showAlert = function(msg) {
		new Boxy('<div>' + msg + '</div>', {title: 'Error', draggable: false, modal: true});
	};
	$.ajaxSetup({
		error: function(x, e){
			switch(x.status) {
				case 0:
					showAlert('You are offline; please check your network connection.');
					break;
				case 401:
					showAlert('You must be logged in to access this resource.');
					break;
				case 403:
					showAlert('You do not have permission to access this resource.');
					break;
				case 404:
					showAlert('The requested resource does not exist on this server.');
					break;
				case 500:
					showAlert('The server encountered an error and the request cannot be completed at this time.');
					break;
				default:
					if(e == 'parsererror'){
						showAlert('Failed to parse server response.');
					}
					else if(e == 'timeout'){
						showAlert('Request timed out.');
					}
					else {
						showAlert('An unknown error has occurred.');
					}	
			}
		}
	});
}
/**
 * Transforms UL element into drop-down menu
 * 
 * @param		object el
 * @return      void
 */
function transformMenu(el) {
	var div = $(this).hide();
	if(div.parent().children('a.side-menu-toggle').length == 0) {
		var toggle	= $('<a class="side-menu-toggle" title="Click To Expand Menu"></a>');
		div.parent().prepend(toggle);
		toggle.bind('click', null, function() {
			if($(this).hasClass('expanded')) {
				$(this).removeClass('expanded').attr('title', 'Click To Expand Menu');
				$(this).parent().children('.side-menu').slideUp();
				$(this).parent().children('select.goTo').slideDown();
			}
			else {
				$(this).addClass('expanded').attr('title', 'Click To Collapse Menu');
				$(this).parent().children('select.goTo').slideUp();
				$(this).parent().children('.side-menu').slideDown();
			}
		});
	}
	var title	= div.find('div');
	var list	= div.find('ul');
	var select 	= $('<select class="goTo"></select>');
	div.parent().append(select);
	select.append('<option class="first" value="">-- ' + title.html() + '</option>');
	$(this).children('ul:first').find('li').each(function() {
		var tmpAnchor	= $(this).find('a').eq(0);
		var optClass	= 'html';
		if(tmpAnchor.attr('href').indexOf('.pdf') > -1) {
			optClass = 'pdf';
		}
		else if(tmpAnchor.attr('href').indexOf('http://') > -1) {
			optClass = 'external';
		}
		select.append('<option class="' + optClass + '" value="' + tmpAnchor.attr('href') + '">' + tmpAnchor.attr('title') + '</option>');
	});
}
/**
 * Asks for confirmation before leaving website
 * 
 * @param		string url
 * @return		void
 */
function confirmLeave(url) {
	site = '<div style="font-weight: bold;">' + url + '</div>';
	Boxy.confirm('You are about to leave www.arroyogrande.org. Click \'OK\' if you wish to proceed to the following URL: ' + site, function() {
		self.location.href = url;
	}, {title: 'Leaving www.arroyogrande.org'});
}
/**
 * Processes JSON form submittal
 * 
 * @param		object json
 * @return		void
 */
function processForm(json) {
	if(json.success) {
		var title	= json.title || 'Result';
		var msg		= json.msg || 'Your request has been processed';
		var html	= '<div>' + msg + '</div>';
		new Boxy(html, {title: title, draggable: false, modal: true});
		setTimeout(function() {
			$('.boxy-wrapper .title-bar .close').click();
		}, 1500);
	}
	else {
		if(json.errors.all != undefined) {
			var html = '<div>' + json.errors.all + '</div>';
			new Boxy(html, {title: 'Error', draggable: false, modal: true});
		}
		for(id in json.errors) {
			var tmpField = $('[name=' + id + ']');
			if(tmpField != undefined) {
				var err = eval('json.errors.' + id) + ' (click to fix)';
				tmpField.addClass('input-error').attr('value', err).bind('focus', null, function() {
					this.value = '';
					$(this).removeClass('input-error');
				});
			}
		}
	}
}
/**
 * Calls all methods in obj
 *
 * @param       object obj
 * @return      void
 */
function initialize(obj) {
    for(method in obj) {
        (obj)[method]();
    }
}
// Object with browser-related methods
var browser = function() {
    return {
        cookieName: 'browserNoNotice',
        getContainer: function() {
            var container = $('div.left');
            if(container.length == 0) {
                container = $('div.content');
            }
            return container;
        },
        check: function() {
            var cookie = $.cookie(browser.cookieName);
            if(cookie != 1) {
                $.get('/browser-notice/', {format: 'html', browser: 'msie', version: $.browser.version}, function(html) {
                    var notice = $('<div id="browser-notice"></div>').html(html).hide();
                    browser.getContainer().prepend(notice);
                    notice.fadeIn('slow');
                }, 'html');
            }
        },
        skip: function() {
            $.cookie(browser.cookieName, 1, {expires: 3650, path: '/'});
            $('div#browser-notice').slideUp('slow');
        }
    };
}();
// Object with location map-related methods
var locationMap = function() {
	return {
		place:		null,
        street:     null,
        city:       null,
        state:      null,
		zip:        null,
		init: function() {
			locationMap.place	= $('#place').html() || $('#street').html();
            locationMap.street  = $('#street').html();
            locationMap.city    = $('#city').html();
            locationMap.state   = $('#state').html();
            locationMap.zip     = $('#zip').html();
			if(locationMap.street != null && locationMap.city != null && locationMap.state != null && locationMap.zip != null) {
				var script = document.createElement("script");
				script.setAttribute('src', 'http://maps.google.com/maps/api/js?sensor=false&async=2&callback=locationMap.load');
				script.setAttribute('type', 'text/javascript');
				document.documentElement.firstChild.appendChild(script);
			}
		},
		load: function() {
            if(locationMap.street && locationMap.city && locationMap.state && locationMap.zip) {
                var address     = locationMap.street + ', ' + locationMap.city + ', ' + locationMap.state + ' ' + locationMap.zip;
                var geocoder    = new google.maps.Geocoder();
                geocoder.geocode({address: address}, function(results, status) {
                    if(status == google.maps.GeocoderStatus.OK) {
                        var mapOpts = {
                            zoom:		16,
                            center:		results[0].geometry.location,
                            mapTypeId:	google.maps.MapTypeId.ROADMAP
                        };
                        var map		= new google.maps.Map(document.getElementById('location-map'), mapOpts);
                        var marker	= new google.maps.Marker({
                            position:	results[0].geometry.location,
                            map:		map,
                            title:		locationMap.place
                        });
                    }
                });
            }
		}
	};
}();
// Function that enables mini-calendar navigation
var miniCalendar = function() {
    $('a.mini-calendar').each(function() {
        $(this).click(function() {
            var name = $(this).attr('name');
            $('#mini-calendar').load(
                '/calendar/mini/',
                {format: 'html', month: name},
                miniCalendar
            );
            return false;
        });
    });
}
// Object with initialization methods for all browsers
safeInit = function() {
    return {
        externalLinks: function() {
			$('a').filter(function() {
				return (this.href != '' && (this.href.indexOf(baseUrl) == -1 && this.href.indexOf('mailto:') == -1));
			}).addClass('external');
        },
		goTo: function() {
			// Private method to navigate to given URL
			go = function(url) {
				if(url != '') {
					if(url.substring(0, 7) == 'http://' || url.substring(0, 8) == 'https://') {
						confirmLeave(url);
					}
					else {
						self.location.href = url;
					}
				}
			};
			$('.goTo').each(function() {
				if(this.tagName == 'SELECT') {
					$(this).bind('change', null, function() {
						go(this.value);
					});
				}
				else if(this.tagName == 'INPUT') {
					$(this).bind('click', null, function() {
						go(this.name);
					});
				}
			});
		},
        imageFade: function() {
            var container   = $('li.splash div');
            var images      = container.attr('class').split('|');
            var total       = images.length;
            var loading     = $('<img style="float: left; padding: 100px 0 0 340px;" src="http://static.arroyogrande.org/assets/images/loading.gif" width="100" height="100"/>');
            var loaded      = 0;
            container.hide();
            if($.browser.msie) {
                if(total == 1) {
                    if($.browser.version.substr(0, 1) == 6) {
                        container.css('position', 'relative').css('top', '-12px');
                    }
                    else if($.browser.version.substr(0, 1) == 7) {
                        container.css('position', 'relative').css('top', '-14px');
                    }
                }
                else {
                    if($.browser.version.substr(0, 1) == 6) {
                        container.css('position', 'relative').css('top', '-300px');
                    }
                }
            }
            container.parent().append(loading);
            for(i = 0; i < total; i++) {
                var img = new Image(780, 300);
                img.src = images[i];
                $(img).bind('load', function() {
                    container.append(this);
                    loaded++;
                    if(loaded == total) {
                        loading.fadeOut('slow').remove();
                        container.fadeIn('slow').cycle({fx: 'fade', duration: 3000});
                    }
                });
            }
        },
        locationMap: function() {
            locationMap.init();
        },
		maxHeight: function() {
			$('.maxHeight').each(function() {
				var height = $(this).height();
				if(height > 200) {
					$(this).css('overflow-y', 'auto')
					.height(200).css('padding-right', '1em');
				}
			});
		},
        miniCalendar: miniCalendar,
        scrollable: function() {
            var root    = $('.scrollable').scrollable({circular: true}).autoscroll({interval: 4000});
            var api     = root.data('scrollable');
            $('.scrollable a.pause').bind('click', function() {
                (scrollState) ? api.stop() : api.play();
                scrollState = !scrollState;
            });
        },
		stripe: function() {
			$('.list tr:even').each(function() {
				$(this).addClass('highlight');
			});
		}
    };
}();
// Object with initialization methods for modern browsers
modernInit = function() {
	return {
		ajax: function() {
            setupAjax();
        },
		corners: function() {
            if(!$.browser.msie) {
                $('.corner').corner();
            }
		},
		emailLinks: function() {
			$('a').filter(function() {
				return (this.href.substring(0, 7) == 'mailto:');
			}).bind('click', function(e) {
				// Prevent redirect
				e.preventDefault();
				var name 	= $(this).html();
				var email	= this.href.substring(7);
				$.get('/contact/email/', {format: 'html', email_to_name: name, email_to: email}, function(html) {
					var title = '<span class="email">Send Email</span>';
					new Boxy(html, {title: title, draggable: false, modal: true, afterShow: modernInit.forms});
				}, 'html');
			});
		},
		externalLinks: function() {
			$('a').filter(function() {
				return (this.href != '' && (this.href.indexOf(baseUrl) == -1 && this.href.indexOf('mailto:') == -1));
			}).bind('click', function(e) {
				// Prevent redirect
				e.preventDefault();
                confirmLeave(new String(this));
			});
		},
		forms: function() {
			$('.charactercount').charactercount();
			$('form.ajax').submit(function() {
				var formObj = $(this);
				$(this).ajaxSubmit({
					url:		this.action + 'format/json/',
					dataType:	'json',
					success:	processForm
				});
				// Remove any error on reset
				formObj.find(':reset').bind('click', null, function() {
					formObj.find('input.text, textarea').each(function() {
						$(this).removeClass('input-error');
					});
					return true;
				});
				return false;
			});
		},
        mainMenu: function() {
			// Private attributes
			var timer				= null;			// Timer object
			var expandTo			= '810';		// Width of expanded portal
			var expandDuration		= 500;			// Duration of expand animation
			var collapseDuration	= 500			// Duration of collapse animation
			// Resests portals state to collapsed
			var reset = function() {
				$('li.portal').each(function() {
					// Prevent scrollbars from showing while collapsing/expanding
					$(this).children('.links').css('overflow-y', 'hidden');
					$(this).animate({width: '30px', queue: false}, collapseDuration);
				});
			};
			// Add animation to each portal when clicked
			$('li.portal a.portal').each(function() {
				var portal		= $(this);
				var portalId	= portal.attr('href');
				portal.parent().children('div.links').each(function() {
					$(this).data('id', portalId);
				});
				portal.bind('click', null, function() {
					if($(this).parent().width() == expandTo) {
                        reset();
						setTimeout(function() {$('li.splash').show();}, collapseDuration);
					}
					else {
						setTimeout(function() {$('li.splash').hide();}, expandDuration);
                        reset();
						$(this).parent().children('.links').each(function() {
                            var isLoaded = $(this).data('ajaxLoaded') || false;
                            if(!isLoaded) {
                                var target = $(this);
                                $.get('/menu/quick-links/portal' + target.data('id'),
                                    {format: 'html'},
                                    function(data, status) {
                                        target.html(data);
                                        target.data('ajaxLoaded', true);
                                        safeInit.externalLinks();
                                        modernInit.externalLinks();
                                    },
                                    'html'
                                );
                            }
						});
						$(this).parent().animate({width: expandTo + 'px', queue: false}, expandDuration, null, function() {
							// Once finished expanding, enable vertical scrollbars
							$(this).children('.links').css('overflow-y', 'auto');
						});
					}
					$(this).blur();
					return false;
				});
			});
        },
		searchBox: function() {
			$('input.keywords').bind('focus', null, function() {
				this.value = '';
				$(this).removeClass('fade');
			}).bind('blur', null, function() {
				if(this.value == '') {
					//this.value = 'Search this site...';
					$(this).addClass('fade');
				}
			});
		},
		sideMenu: function() {
			$('div.side-menu').each(transformMenu);
		}
	}
}();
/**
 * Initializes the page when ready
 *
 * @return      void
 */
$(document).ready(function() {
    // Check for broken versions of IE
    if($.browser.msie && $.browser.version.substr(0, 1) < 8) {
        $('div.links').css('display', 'none');
        browser.check();
    }
    else {
        // Call modern object methods
        initialize(modernInit);
    }
    // Call safe object methods
    initialize(safeInit);
});