function initMap(){
	var locations = ["brooklyn","manhattan","bronx","queens","staten-island"];
	if($(".map").length <= 0){return;}
	var current_dropdown;
    var current_borough;
	$(locations).each(function(i,e){
        if($('.menu li.'+e).length == 0){return;}
		$('.map li.'+e).mouseover(function(){
			if(typeof current_dropdown != "undefined" && !current_dropdown.hasClass(e)){
			    //current_dropdown.trigger("mouseleave");
    			$('.map-hilight.'+current_borough).stop().fadeOut(200);
	    		$('.menu li.'+current_borough).removeClass("hover");
			}
			//show map
            if(!$(".map-hilight."+e).is(":visible") ){    
    			$('.map-hilight.'+e).stop();
            }
    			$('.map-hilight.'+e).fadeIn(
                    function(){$('.map-hilight.'+e).css("opacity","1");}
                );
            
			//show menu
			$('.menu li.'+e).addClass("hover");
		    current_dropdown = $('.menu li.'+e);
            current_borough = e;
			
		}).mouseleave(function () {
                    //$('.menu li.'+e).trigger("mouseleave");
                });

		$('.menu li.'+e).mouseleave(function(){
			$('.map-hilight.'+e).stop().fadeOut();
			$('.menu li.'+e).removeClass("hover");
		});
		$('.menu li.'+e).mouseover(function(){
			$('.map li.'+e).trigger("mouseover");
		});
		$(".map-hilight."+e).click(function(){
			$('.menu li.'+e).removeClass("hover");
		});
		$('.menu li.'+e).mouseover(function(){
			$('.map li.'+e).trigger("mouseover");
		});
		$(".map-hilight."+e).click(function(){
			$('.menu li.'+e).trigger("mouseleave");
		});
	});
    
}

function initDropdowns(){
    $( "#sel-programs" ).change( function() {
        var new_path = $( this ).val();

        if( new_path != '' )
            window.location = new_path;
    });

    $( "#sel-school" ).change( function() {
        var new_path = $( this ).val();

        if( new_path != '' )
            window.location = new_path;
    });
}

function initPage()
{
    /*
	clearFormFields({
		//clearInputs: true,
		clearInputs: false,
		clearTextareas: true,
		passwordFieldText: true,
		addClassFocus: "focus",
		filterClass: "default"
	});
    */
    //* initializing form
    var google_input = $(".google-search input[type='text']");
    google_input.focus(function(){
        google_input.addClass("focus");
    });
    google_input.blur(function(){
        if(google_input.attr("value").length == 0 ){
            google_input.removeClass("focus");
        }
    });
    google_input.trigger("focus").trigger("blur");
	initBrowserDetect();
}
function clearFormFields(o)
{
	if (o.clearInputs == null) o.clearInputs = true;
	if (o.clearTextareas == null) o.clearTextareas = true;
	if (o.passwordFieldText == null) o.passwordFieldText = false;
	if (o.addClassFocus == null) o.addClassFocus = false;
	if (!o.filter) o.filter = "default";
	if(o.clearInputs) {
		var inputs = document.getElementsByTagName("input");
		for (var i = 0; i < inputs.length; i++ ) {
			if((inputs[i].type == "text" || inputs[i].type == "password") && inputs[i].className.indexOf(o.filterClass)) {
				inputs[i].valueHtml = inputs[i].value;
				inputs[i].onfocus = function ()	{
					if(this.valueHtml == this.value) this.value = "";
					if(this.fake) {
						inputsSwap(this, this.previousSibling);
						this.previousSibling.focus();
					}
					if(o.addClassFocus && !this.fake) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				inputs[i].onblur = function () {
					if(this.value == "") {
						this.value = this.valueHtml;
						if(o.passwordFieldText && this.type == "password") inputsSwap(this, this.nextSibling);
					}
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
				if(o.passwordFieldText && inputs[i].type == "password") {
					var fakeInput = document.createElement("input");
					fakeInput.type = "text";
					fakeInput.value = inputs[i].value;
					fakeInput.className = inputs[i].className;
					fakeInput.fake = true;
					inputs[i].parentNode.insertBefore(fakeInput, inputs[i].nextSibling);
					inputsSwap(inputs[i], null);
				}
			}
		}
	}
	if(o.clearTextareas) {
		var textareas = document.getElementsByTagName("textarea");
		for(var i=0; i<textareas.length; i++) {
			if(textareas[i].className.indexOf(o.filterClass)) {
				textareas[i].valueHtml = textareas[i].value;
				textareas[i].onfocus = function() {
					if(this.value == this.valueHtml) this.value = "";
					if(o.addClassFocus) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				textareas[i].onblur = function() {
					if(this.value == "") this.value = this.valueHtml;
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
			}
		}
	}
	function inputsSwap(el, el2) {
		if(el) el.style.display = "none";
		if(el2) el2.style.display = "inline";
	}
}
if (window.addEventListener)
	window.addEventListener("load", initPage, false);
else if (window.attachEvent)
	window.attachEvent("onload", initPage);
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('9 u=k(){9 g=/^([^#.>`]*)(#|\\.|\\>|\\`)(.+)$/;k u(a,b){9 c=a.J(/\\s*\\,\\s*/);9 d=[];n(9 i=0;i<c.l;i++){d=d.v(o(c[i],b))};6 d};k o(a,b,c){a=a.z(" ","`");9 d=a.r(g);9 e,5,m,7,i,h;9 f=[];4(d==8){d=[a,a]};4(d[1]==""){d[1]="*"};4(c==8){c="`"};4(b==8){b=E};K(d[2]){w"#":7=d[3].r(g);4(7==8){7=[8,d[3]]};e=E.L(7[1]);4(e==8||(d[1]!="*"&&!x(e,d[1]))){6 f};4(7.l==2){f.A(e);6 f};6 o(7[3],e,7[2]);w".":4(c!=">"){5=p(b,d[1])}y{5=b.B};n(i=0,h=5.l;i<h;i++){e=5[i];4(e.C!=1){q};7=d[3].r(g);4(7!=8){4(e.j==8||e.j.r("(\\\\s|^)"+7[1]+"(\\\\s|$)")==8){q};m=o(7[3],e,7[2]);f=f.v(m)}y 4(e.j!=8&&e.j.r("(\\\\s|^)"+d[3]+"(\\\\s|$)")!=8){f.A(e)}};6 f;w">":4(c!=">"){5=p(b,d[1])}y{5=b.B};n(i=0,h=5.l;i<h;i++){e=5[i];4(e.C!=1){q};4(!x(e,d[1])){q};m=o(d[3],e,">");f=f.v(m)};6 f;w"`":5=p(b,d[1]);n(i=0,h=5.l;i<h;i++){e=5[i];m=o(d[3],e,"`");f=f.v(m)};6 f;M:4(c!=">"){5=p(b,d[1])}y{5=b.B};n(i=0,h=5.l;i<h;i++){e=5[i];4(e.C!=1){q};4(!x(e,d[1])){q};f.A(e)};6 f}};k p(a,b){4(b=="*"&&a.F!=8){6 a.F};6 a.p(b)};k x(a,b){4(b=="*"){6 N};6 a.O.G().z("P:","")==b.G()};6 u}();k Q(a,b){9 c=u(a);n(9 i=0;i<c.l;i++){c[i].R=k(){4(t.j.H(b)==-1){t.j+=" "+b}};c[i].S=k(){4(t.j.H(b)!=-1){t.j=t.j.z(b,"")}}}}4(D.I&&!D.T){D.I("U",V)}',58,58,'||||if|listNodes|return|subselector|null|var||||||||limit||className|function|length|listSubNodes|for|doParse|getElementsByTagName|continue|match||this|parseSelector|concat|case|matchNodeNames|else|replace|push|childNodes|nodeType|window|document|all|toLowerCase|indexOf|attachEvent|split|switch|getElementById|default|true|nodeName|html|hoverForIE6|onmouseover|onmouseout|opera|onload|ieHover'.split('|'),0,{}))
/* line above breaks my emacs coloring' */
/*parametrs [selector, hover_class]*/
function ieHover() {
	hoverForIE6(".menu li", "hover");
	hoverForIE6(".submit", "submit-hover");
}
function initBrowserDetect()
{
	var u = navigator.userAgent.toLowerCase();
	var _html = document.getElementsByTagName("html")[0];
	
	if(is("win")) addClass("win");
	else if(is("mac")) addClass("mac");
	else if(is("linux") || is("x11")) addClass("linux");
	
	if(is("msie 8.0")) addClass("ie8");
	else if(is("msie 7.0")) addClass("ie7");
	else if(is("msie 6.0")) addClass("ie6");
	else if(is("firefox/2")) addClass("ff2");
	else if(is("firefox/3")) addClass("ff3");
	else if(is("opera") && is("version/10")) addClass("opera10");
	else if(is("opera/9")) addClass("opera9");
	else if(is("safari") && is("version/3")) addClass("safari3");
	else if(is("safari") && is("version/4")) addClass("safari4");
	else if(is("safari") && is("version/5")) addClass("safari5");
	else if(is("chrome")) addClass("chrome");
	else if(is("safari")) addClass("safari2");
	else if(is("unknown")) addClass("unknown");
	
	if(is("msie")) addClass("trident");
	else if(is("applewebkit")) addClass("webkit");
	else if(is("gecko")) addClass("gecko");
	else if(is("opera")) addClass("presto");
		
	function is(browser)
	{
		if(u.indexOf(browser) !=-1) return true;
	}
	function addClass(_class)
	{
		_html.className += (" " + _class);
	}
}

function initHomepageImage(){
    if( $(".center_images").length <= 0 ){ // If no images or does not exist, exit
        return;
    }
    var all_images = $(".center_images img"); // Get array of all images
    
    all_images.css("display","none"); // Hide all images
    var random_index = Math.floor(Math.random() * $(".center_images img").length); // 0 to length-1
    $(all_images[random_index]).css("display","block"); // Randomly choose one to display
}

function initSlideshow(){
    $('.frontend-slideshow').frontendSlideshow();
    return;
    if($('.gal-holder').length > 0){
        var loaded_count = 0;
        var img_ref_count = $('.frontend-slideshow img').length;
            //* we have to wait until the images load before we create the slideshow
        $('.frontend-slideshow img').load(function(){
            loaded_count++;
            if(loaded_count == img_ref_count){
                $('.frontend-slideshow').frontendSlideshow();
            }
        });
    }
    
}

    function initPhotoSlideshow()
    {
        $( '.images-list  a' ).colorbox({
            //loop: false,
            rel: 'group1',
            transition: 'elastic',
            onLoad: function () {
                //positionColorbox();
            },
            onComplete: function () {
                //$(window).unbind('resize.cbox');
                //positionColorbox();
            }/*,
            onOpen: function () {
                $( '#cboxDownload' ).remove();
                var downloadHTML = '<div id="cboxDownload">DOWNLOAD</a>';
                $( '#cboxContent' ).append( downloadHTML );
                $( '#cboxDownload' ).click( function () {
                    var item = $.colorbox.element();
                    var originalImage = item.find( '.original-image' );
                    var originalImageURL = originalImage.text();

                    window.open( originalImageURL );
                    return false;
                } );

            }*/
            
        });

    } // initPhotoSlideshow

function initForms()
{
    // Setup international address widgets
    $( '.rtg-intl_address' ).rubyInternational();

    // Setup 
    $( '.ruby-commerce-form' ).simpleECommerce();

}



function initP2P(){
    if($('.tabset').length > 0){
        // Hide all content, display details div
        $(".tab-content").hide();
        
        $('.tabset li a').click(function( evt, params ){ // When a nav is clicked
            // Deactivate all navs, then activate the clicked one
            $('.tabset li a').removeClass("tab-active");
            $(this).addClass("tab-active");
            
            // Hide all content divs, then enable only the desired one
            $('.tab-content').hide();

            var tabId = $(this).attr( 'id' );
            var tabContent = tabId == 'nav1' ? $( '#tab1' )
                           : tabId == 'nav2' ? $( '#tab2' )
                           :                   $( '#tab3' )
                           ;

            if( typeof params !== 'undefined' 
                && typeof params.tab_content_id != 'undefined' ) {
                tabContent = $( params.tab_content_id );
            }

            tabContent.show();

            return false;
        })

        $('.tab-content .container').click(function(){ // When bottom donate is clicked
            $( '#nav2' ).trigger( 'click' );
        })
        
            // The default tab open
        if( $( '.ruby-commerce-form-peer .ui-state-error' ).length > 0 ) {
            $( '#nav2' ).trigger( 'click' );
        }
        else if( $( '.ruby-commerce-form-peer .ruby-commerce-form-complete' ).length > 0 ) {
            $( '#nav2' ).trigger( 'click', { tab_content_id : '#tab99' } );
        }
        else {
            $( '#nav1' ).trigger( 'click' );
        }

    }
}

var events_per_page = 5;
function initCalendar(){
    //var temp_test = Date.compare(new Date(), new Date().clearTime());
    if($(".calendar-template").length == 0){
        return;
    }
    //console.log($("#datepicker"));
    $("#datepicker").datepicker({
            onSelect: function(dateText, inst) {
                //console.log(dateText, inst);
                //console.log(Date.parse( dateText) );
                var parsedDate_selected = Date.parse( dateText) ;
                var all_events = $("ul.events li");
                all_events.removeClass("hidden-by-cal");
                all_events.each(function(i,e){
                    var temp_start_date = $(e).find(".date-start-handler").text() || $(e).find(".date-end-handler").text() ;
                    var temp_end_date = $(e).find(".date-end-handler").text() || $(e).find(".date-start-handler").text();
                    if(temp_end_date.length == 0){
                        $(e).addClass("hidden-by-cal");
                        return; 
                    }
                    var start_date_string = temp_start_date.substr(6) + "-" +  temp_start_date.substr(0,2)+"-"+temp_start_date.substr(3,2);
                    var end_date_string = temp_end_date.substr(6) + "-" +  temp_end_date.substr(0,2)+"-"+temp_end_date.substr(3,2);
                    var date_string = dateText.substr(6) + "-" +  dateText.substr(0,2)+"-"+dateText.substr(3,2);
                    //console.log("selected", date_string, "start_date", start_date_string, end_date_string);


                    var parsed_end_date = Date.parse( temp_end_date);  

                    //console.log(temp_end_date.length, "TEMP END DATE", dateText, temp_end_date);
                    //console.log(parsed_end_date);
                    //if(Date.compare( parsed_end_date, parsedDate_selected) == 0 ){
                    /*
                    if(Date.compare( parsed_end_date, parsedDate_selected) == 0 ){
                        console.log("equals");
                    }*/
                    if(  date_string < start_date_string || date_string > end_date_string){
                        $(e).addClass("hidden-by-cal");
                    }
                });
                if($("ul.events li:not('.hidden-by-cal')").length == 0){
                    $(".no-events").show();
                    $(".hidden-by-cal").hide();
                    $(".pagination").hide();
                }
                else{
                    $(".no-events").hide();
                    $(".pagination").show();
                }
                        calendarPaginate();
            }
    });

    //* show all events
    $(".all-events-btn").click(function(){
        //console.log("all events clicked");
        $(".no-events").hide();
        $(".pagination").show();
        var all_events = $("ul.events li");
        all_events.removeClass("hidden-by-cal");
        all_events.show();
        calendarPaginate();
        $("#datepicker").datepicker("setDate", null);
    });

    //* setup pager
    var all_events = $("ul.events li");
    var pager =  $(".pagination");
    //* NOTE: for filtering via calendar, give events that are hidden a "hidden-by-cal" class
    function calendarPaginate(){
        //var all_visible_events = $("ul.events li:visible");
        var all_visible_events = $("ul.events li:not(.hidden-by-cal)");
        var num_of_pages = Math.ceil(all_visible_events.length / events_per_page);
        var num_of_page_anchors = $(".pagination li").length;
        if(num_of_page_anchors < num_of_pages){
            //* insert more anchors
            for(var i = num_of_page_anchors+1; i<= num_of_pages; i++ ){
                $(".pagination ul").append($("<li><a class='pager' href='#'>"+i+"</a></li>"));
            }
        }
        else if(num_of_page_anchors > num_of_pages){
            //* delete some pages
            var all_page_anchors = $(".pagination li");
            for(var i =  num_of_page_anchors-1; i >= num_of_pages; i-- ){
                $(all_page_anchors[i]).remove();
            }
        }
        //* setup events
        var all_page_anchors = $(".pagination li");
        all_page_anchors.each(function(i,e){
            $(e).unbind("click.calendar");
            $(e).bind("click", function(){
                all_page_anchors.removeClass("active");
                $(e).addClass("active");
                //* hide some event li's
                $("ul.events li").show();
                var visible_events = $("ul.events li:not(.hidden-by-cal)");
                var start_pos = (parseInt($(e).text()) -1 )* events_per_page;
                var end_pos = start_pos + 5;
                /*
                if(end_pos > visible_events.length -5){
                    end_pos = visible_events.length;
                }
                */
                $("ul.events li").hide();
                for(var i = start_pos; i< end_pos; i++){
                    $(visible_events[i]).show();
                }
                return false;
            });
            if(i == 0){
                $(e).trigger("click");
            }
        });
        //console.log(all_visible_events, num_of_pages);
    }
    calendarPaginate();
}

function externalLinkInit(){
    //console.log(location.protocol+"//"+location.host);
    //$('a:regex(href, (?<!'+location.host+').* )').each(function(index, element){
    $('a:not(.target-blank)').each(function(index, element){
        var temp_str = $(element).attr('href');
        if(temp_str == undefined){return;}
        if((temp_str.charAt(0)!= "?" && temp_str.charAt(0)!= "#" && !temp_str.match(location.host) && temp_str.charAt(0)!="/" && !temp_str.match("mailto:") && !temp_str.match("javascript:")) || temp_str.match(".pdf")){
            //$(element).css("target-name", "new"); //not support as of yet
            //$(element).css("target-new", "tab"); //not supported as of yet 
            $(element).click(function(){window.open(this.href); return false;});
        }
    });
    
}

function initVideo() {
    
    $( '.fe-video' ).frontendVideo({
        jwplayer_params:{
        flashplayer: '/javascript/ruby/jwplayer/player.swf',
        skin: '/images/flash/beelden/beelden.xml'
        }
    });
}

// Apply an animate fix to jquery 1.4.4, see RT#10930 and:
// http://bugs.jquery.com/ticket/7287#comment:17
if( jQuery.fn.jquery === "1.4.4" ) { // Bug is fixed in 1.5, so only apply if we are still using 1.4.4

    $.fx.prototype.cur = function() { // we are overwriting this function to remove limiting of the size of the

        if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) {
            return this.elem[ this.prop ];
        }

        var r = parseFloat( jQuery.css( this.elem, this.prop ) );
        return r || 0; // copied this from from jquery-1.5.js
    } // $.fx.prototype.cur

} // if jquery is 1.4.4


$(document).ready(function(){
    initHomepageImage();
	initMap();
	initDropdowns();
	initSlideshow();
	initPhotoSlideshow();
	initP2P();
    initForms();
    initCalendar();
    externalLinkInit();
    initVideo();
});




