// catch console.log 
if( !window.console ){
	window.console = new function(){
		this.log = function(str){};
		this.dir = function(str){};
	};
};
/*
initBodyClass:
adds class to body (for CSS styles that depend on JavaScript)
*/
function addBodyClass(){
	var el = document.getElementsByTagName("body")[0];	
	el.className += " js";
}
/* 
toggleFinder:
sets up finder to toggle open and close
*/
function toggleFinder(){
	$( 'a.toggle' ).click( function(){
		s = doFinderToggle();
		return s;
	} ); 
};

function doFinderToggle(){
	if( $.browser.msie && $.browser.version < 7 ){
		return true;
	};
	
	hid = $( '#gmaxfooter .i' ).is(':hidden' );
	
	if( hid && getFindRideCookie() ){
		$( '#gmaxfooter .i' ).slideToggle( 'normal', doRideSearch );
		$( '#gmaxfooter a.toggle' ).toggleClass("toggle-on");
		return false;
	} else if( !hid ){
		setFindRideCookie();
	};
	
	$( '#gmaxfooter .i' ).slideToggle( 'normal' );
	$( '#gmaxfooter a.toggle' ).toggleClass("toggle-on");
	
	return false;
};

/* 
toggleDD:
sets up styled dropdowns to toggle open and close
*/
function toggleDD(){
	$( '.dd h4' ).click( function(){
		$(this).next().slideToggle();
	} ); 
};

/* 
addPrintLink:
adds "print this page" link to DOM
*/
function addPrintLink(){
	var e = $( '.head #share' )[0];
	if(!e) return false;
	
	// create <a>
	var anchor = document.createElement('a' );
	var anchorText = document.createTextNode('Print This Page' );
	anchor.setAttribute('class','print' );
	anchor.onclick = function(){ window.print(); return false; };
	anchor.appendChild(anchorText);
	
	// add <a> to DOM
	e.appendChild(anchor);
};

function emailModal(){
	$('li.email a').click(function(){
		x = this;
		
		p = $( x );
		openModal( p );
	
		$.ajax({
			success: function(json){
				showEmail(json, x, -142);
			},
			url: x.href
		});
		return false;
	});
};

function showEmail( json, x, offsetH ){
	insertIntoModal( json, validateModal, offsetH );
};

function validateModal(){
	$('form#email-page').ajaxForm({
		success: sentEmail
	} );
};

function sentEmail( json ){
	insertIntoModal(json);
	validateModal();
};

function getFindRideCookie(){
	x = $.cookie('findARide' );
	try{
		c = $.secureEvalJSON(x);
		
		trails = $('#rbTrails').attr( 'checked', c.trails );
		routes = $('#rbRoutes').attr( 'checked', c.routes );
		groups = $('#rbGroup').attr( 'checked', c.groups );
		loc = $('#ddLocation').val( c.loc );
		
		return true;	
	} catch(e){
		return false;
	};
};

function setFindRideCookie(){
	
	t = $('#rbTrails').attr('checked' );
	r = $('#rbRoutes').attr('checked' );
	g = $('#rbGroup').attr('checked' );
	l = $('#ddLocation').val();
	
	v = {
		trails: t,
		routes: r,
		groups: g,
		loc: l
	};
	
	c = $.toJSON(v)
	
	$.cookie('findARide', c , { expires: 7, path: '/', domain: 'dev.bikeoregon' } );
	
	return v;
};
/*
findARide:
shows results map after a search has been done
*/
function findARide(){
	$('#gmaxfooter form').submit( function(){
	
		doRideSearch();
		
		return false;
	} );
};

function toggleSubmenu(){

	$( 'a.button-aboutus' ).hover( function(){
		//alert("slut");
		s = gmaxReveal();
		var baboutus = document.getElementById('button-aboutus');
		if (baboutus.className == "button-aboutus") {
			baboutus.className = "button-aboutus-selected";
		} else {
			baboutus.className = "button-aboutus";	
		}
		return s;
	} ); 
	
	$( 'a.button-aboutus-selected' ).hover( function(){
		//alert("slut");
		s = gmaxReveal();
		return s;
	} ); 


};


function gmaxRevealShow() {
//	$( '#gmaxfooter .i' ).slideToggle( 'normal', doRideSearch );
	
	 
	 $('#gmaxsubmenu .i').slideToggle('normal');
	//alert("hi?");
	return true;
};

function gmaxReveal() {
//	$( '#gmaxfooter .i' ).slideToggle( 'normal', doRideSearch );
	
	 
	 $('#gmaxsubmenu .i').slideToggle('normal');
	//alert("hi?");
	return true;
};

function gmaxReveal2() {
//	$( '#gmaxfooter .i' ).slideToggle( 'normal', doRideSearch );
	
	 
	 $('#gmaxsubmenu2 .i').slideToggle('normal');
	//alert("hi?");
	return true;
};

function doRideSearch(){
	// show map	
	$('#gmaxfooter-results').css({
	    position:'static'
	});
	
	setTimeout( function(){
	    swf = swfobject.getObjectById("gmaxfooter-swf");
	
		v = setFindRideCookie();
		
		var a = '';
		
		try{
			swf.searchRides( v.trails, v.routes, v.groups, v.loc );
			a = ( '\ntrails: '+ v.trails + '\nroutes: '+ v.routes + '\ngroups: '+ v.groups + '\nloc: '+ v.loc );
		} catch(e){
			// boo
		};
		
	}, 500);
};
/* 
modalWindow 
*/
(function($){
var openmodals = 0;
//overlay on background
openModal = function( e, offsetH ){
	openmodals ++;
	
	if( openmodals > 0){
		closeModal();
	};
	
	$( 'body' ).append(
		'<div id="modal"><div class="i"><div class="i"><div class="i"><img src="/img/icons/spinner.gif" alt="" /></div></div></div></div>'
	);
	
	if( offsetH ){
		pos = e.offset();
		$( '#modal' ).css( {
			left: pos.left - 50 + offsetH,
			top: pos.top - 22,
			width: '104px'
		} );
			
	} else if( typeof(e) != 'undefined' ){
		if( e.jquery ){
			//jquery object
			pos = e.offset();
			$( '#modal' ).css( {
				left: pos.left - 30,
				top: pos.top - 30,
				width: '104px'
			} );
		} else {
			//mouse event
			$( '#modal' ).css( {
				left: e.pageX - 42 + "px",
				top: e.pageY - 42 +"px",
				width: '104px'
			} );
		};
	};
};

closeModal = function(){
	openmodals --;
	$( '#modal' ).remove();
};

insertIntoModal = function( json, callback, offsetH ){
	
	try {
		eval( 'result = '+json );
		cont = result.html;
	} catch(e){
		cont = json;
	};
	
	$( '#modal div div div' ).html( cont + '<a title="Close" class="close">Close</a>' );
	
	if( offsetH){
		$( '#modal' ).css({
			left: pos.left - 50 + offsetH
		});
	};
	
	$( '#modal' ).effect( "bounce", { 
		distance: 5, 
		times: 2 
	}, 200, function(){
		$(this).addClass('on' );
	}).animate({
		marginLeft: '-165px',
		width: '430px'
	}, { duration: 100, queue: false });
	
	if( callback ){
		callback();
	};
	
	$( '.cancel, .close' ).click( function(){
		closeModal();
		return false;
	} );
};	
jQuery.modal = function( options, callback ){
	
	settings = jQuery.extend({
		e: jQuery.Event(),
		url: '/'
	}, options);
	
	href = settings.url;
	e = settings.e;
	
	openModal(e);
	
	jQuery.ajax( {
		success: function( json ){
			insertIntoModal( json, callback );
		},
		url: href
	} );
};
	
})(jQuery);

/*
cookies
*/
jQuery.cookie = function(name, value, options){
    if(typeof value != 'undefined'){ 
        options = options || {};
        if(value === null){
            value = '';
            options.expires = -1;
        };
        var expires = '';
        if(options.expires && (typeof options.expires == 'number' || options.expires.toUTCString) ){
            var date;
            if(typeof options.expires == 'number'){
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000) );
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
       
        var path = options.path ? '; path=' + (options.path):'';
        var domain = options.domain ? '; domain=' + (options.domain):'';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('' );
    } else { 
        var cookieValue = null;
        if(document.cookie && document.cookie != ''){
            var cookies = document.cookie.split(';' );
            for (var i = 0; i < cookies.length; i++){
                var cookie = jQuery.trim(cookies[i]);
                if(cookie.substring(0, name.length + 1) == (name + '=') ){
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1) );
                    break;
                };
            };
        };
        return cookieValue;
    };
};
(function($){   
    function toIntegersAtLease(n){    
        return n < 10 ? '0' + n : n;
    };
    Date.prototype.toJSON = function(date){
        return this.getUTCFullYear()   + '-' +
		toIntegersAtLease(this.getUTCMonth()) + '-' +
		toIntegersAtLease(this.getUTCDate() );
    };
    var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;
    var meta = {
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '"' : '\\"',
        '\\': '\\\\'
    };
        
    $.quoteString = function(string){
        if(escapeable.test(string) ){
            return '"' + string.replace(escapeable, function (a){
                var c = meta[a];
                if(typeof c === 'string'){
                    return c;
                }
                c = a.charCodeAt();
                return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
            }) + '"';
        };
        return '"' + string + '"';
    };
    
    $.toJSON = function(o, compact){
        var type = typeof(o);
        
        if(type == "undefined")
            return "undefined";
        else if(type == "number" || type == "boolean")
            return o + "";
        else if(o === null)
            return "null";
        
        // Is it a string?
        if(type == "string"){
            return $.quoteString(o);
        };
        
        // Does it have a .toJSON function?
        if(type == "object" && typeof o.toJSON == "function"){
            return o.toJSON(compact);
        };
        
        // Is it an array?
        if(type != "function" && typeof(o.length) == "number"){
            var ret = [];
            for (var i = 0; i < o.length; i++){
                ret.push( $.toJSON(o[i], compact) );
            }
            if(compact)
                return "[" + ret.join(",") + "]";
            else
                return "[" + ret.join(", ") + "]";
        };
        
        // If it's a function, we have to warn somebody!
        if(type == "function"){
            throw new TypeError("Unable to convert object of type 'function' to json.");
        };
        
        // It's probably an object, then.
        var ret = [];
        for (var k in o){
            var name;
            type = typeof(k);
            
            if(type == "number")
                name = '"' + k + '"';
            else if(type == "string")
                name = $.quoteString(k);
            else
                continue;  //skip non-string or number keys
            
            var val = $.toJSON(o[k], compact);
            if(typeof(val) != "string"){
                // skip non-serializable values
                continue;
            };
            
            if(compact)
                ret.push(name + ":" + val);
            else
                ret.push(name + ": " + val);
        };
        return "{" + ret.join(", ") + "}";
    };
    
    $.compactJSON = function(o){
        return $.toJSON(o, true);
    };
    
    $.evalJSON = function(src){
        return eval("(" + src + ")");
    };
    
    $.secureEvalJSON = function(src){
        var filtered = src;
        filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@' );
        filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']' );
        filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '' );
        
        if(/^[\],:{}\s]*$/.test(filtered))
            return eval("(" + src + ")");
        else
            throw new SyntaxError("Error parsing JSON, source is not valid.");
    };
})(jQuery);

/*
execute scripts on DOM load
*/
$(function(){
	//addBodyClass();
	//findARide();
	toggleFinder();
	toggleDD();
	toggleSubmenu();
	//addPrintLink();
	//emailModal();
	//getFindRideCookie();
});
