// JavaScript Document 
$(function(){ 

	// innerfade - http://medienfreunde.com/lab/innerfade/   
	$('#fader .dm_widget_inner p').innerfade({speed: 700, timeout: 4000, type: 'sequence', containerheight: '680px'});
        $('#fader .dm_widget_inner').innerfade({speed: 700, timeout: 4000, type: 'sequence', containerheight: '680px'});

	$('.sidebar_fader').innerfade({speed: 700, timeout: 4000, type: 'sequence', containerheight: '70px'});
        $('.sidebar_fader').innerfade({speed: 700, timeout: 4000, type: 'sequence', containerheight: '70px'});

	$("ul.sf-menu").supersubs({ 
		minWidth:    12,   // minimum width of sub-menus in em units 
		maxWidth:    27,   // maximum width of sub-menus in em units 
		extraWidth:  1     // extra width can ensure lines don't sometimes turn over 
						   // due to slight rounding differences and font-family 
	}).superfish();  // call supersubs first, then superfish, so that subs are 
					 // not display:none when measuring. Call before initialising 
					 // containing tabs for same reason. 
					 

        // load the google map if the current page has load() function
        if (typeof load == 'function')
        load();


        //// calendar cell hover
        $('a.cellBody').hover(
            function() {
                $(this).css('overflow', 'auto');
            },
            function() {
                $(this).css('overflow', 'hidden');
            }
        );


    /* attach ajax behaviors for changing the month */
    $.calendarAttachBehaviors();
   
			 
});



/*******  subscribe sidebar module **********/
function is_valid_email( address )
{
	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
	if( !emailReg.test( address ) )
		return false;
	else
		return true;
}
$(function()
{
	$("form#frm_subscribe input[type=text]")
	.focus( function(){
		if ( $(this).val() == 'Your name' || $(this).val() == 'Your email address'  )
		{
			$(this).val( '' );
		}
	})
	.blur( function() {
		if ( $(this).val() == '' )
		{
			if ( $(this).attr( 'name' ) == 'name' )
				$(this).val( 'Your name' );
			if ( $(this).attr( 'name' ) == 'email' )
				$(this).val( 'Your email address' );
		}
	});

	$("form#frm_subscribe").submit(function(){

		if ( $( 'input[name=name]', this).val() == 'Your name' || $( 'input[name=name]', this).val() == '' )
		{
			alert( 'Please provide your name in the field provided' );
			$( 'input[name=name]', this).focus();
			return false;
		}

		if ( $( 'input[name=email]', this).val() == 'Your email address' || $( 'input[name=email]', this).val() == '' || (!is_valid_email( $( 'input[name=email]', this).val() )))
		{
			alert( 'Please provide your email address in the field provided' );
			$( 'input[name=email]', this).focus();
			return false;
		}


		$( "#frm_subscribe_submit" ).hide( "fast" );
		$( "img.processing", this ).show( "fast" );
		$.post("/index.php/+/main/contact", $("form#frm_subscribe").serialize(), function( html ) {
			$("form#frm_subscribe").html( html );
		});
		return false;

	});

});




















  jQuery.calendarAttachBehaviors = function(){


    $("#activityCalendar a[rel^='prettyPhoto']").unbind('click');
    $("#activityCalendar a[rel^='prettyPhoto']").prettyPhoto({
    	default_width: 550, 
    	allowresize: false
    });

    // change months
    $('#activityCalendar #monthWrap h2 a').click(function(){
        $.showLoading('Loading Month');
      $.get($(this).attr('href'), $.updateCalendar);
      return false;
    });

    $('#Exhibitions').click(function() {

        if ($(this).is(':checked'))
            $('.exhibitions').slideDown('slow');
        else
            $('.exhibitions').slideUp('slow');
    });

    $('#Events').click(function() {

        if ($(this).is(':checked'))
            $('.events').slideDown('slow');
        else
            $('.events').slideUp('slow');
    });

    $('#Classes').click(function() {

        if ($(this).is(':checked'))
            $('.klasses').slideDown('slow');
        else
            $('.klasses').slideUp('slow');
    });

//    $("a[rel^='prettyPhoto']").prettyPhoto();

    // pretty photo
   
    //$.loadAndAttachPrettyPhoto();

//    // add events
//    $('#maintable a.cellBody').each(function(){
//      $(this).attr('href', $(this).attr('href') + '?iframe=true&width=700&height=400');
//    }).prettyPhoto({onloadcallback: $.assignCallback});
//
//    // edit events
//    $('#mainGrid a.edit').each(function(){
//		  $(this).attr('href', $(this).attr('href') + '?iframe=true&width=700&height=400');
//	  }).prettyPhoto({onloadcallback: $.assignCallback});

  }

//  jQuery.assignCallback = function(link)
//  {
//    if($(link).attr('href').indexOf('calendar/add') > 0)
//    {
//      $('a.pp_close').click($.insertActivity);
//    }
//    else if($(link).attr('href').indexOf('calendar/edit') > 0)
//    {
//      $('a.pp_close').click($.editActivity);
//    }
//  }

	jQuery.insertActivity = function()
	{
	  $.showLoading('Adding Activity/s');
    $('#pp_full_res iframe').contents().find('.calendar_widget').each(function(){
		var activity_id = $(this).attr('class').replace('calendar_widget activity_', '');
		var input_element_id_parts = $('.inputs span:visible input', this).attr('id').split('_');
		var unit_type_id = input_element_id_parts[2];

		// convert the intensity scale id to real values
		var intensity_scale_id = $('input.amount2.inputB', this).val().split('%');
		var intensity = $.convertIntensity(intensity_scale_id[0]);
		var url_date_parts = $('#pp_full_res iframe').attr('src').split('/');
		var url_date_parts_size = url_date_parts.length;
		$.post('/calendar/insert', {
        ActivityTypeID: activity_id,
        ActivityValue: $('.inputs span:visible input', this).val(),
        UnitTypeID: unit_type_id,
        // ConversionFactor: 'xxx', Not needed for the moment
        // ConversionUnitTypeID: 'xxx', Not needed for the moment
        IntensityScaleID: intensity,
        ActivityDate: url_date_parts[url_date_parts_size -1] + '/' + url_date_parts[url_date_parts_size-2] + '/' + url_date_parts[url_date_parts_size-3]
      }, function(xml){
			$.showLoading('Refreshing Calendar');
			$refresh_url = '/calendar/' + url_date_parts[url_date_parts_size-3] + '/' + url_date_parts[url_date_parts_size-2];
			// if this is IE6, do a page refresh rather than an AJAX one (IE6 is shit)
			// use a random number in the "unique" param to make sure a cached version isnt displayed
			if($.browser.msie && parseInt($.browser.version) == 6)
			{
			  document.location.href = $refresh_url + '?unique=' + Math.floor(Math.random()*100001) + '#mainGrid';
			} else {
			  $.get($refresh_url, $.updateCalendar);
			}
      });
    });
    return false;
	}

	jQuery.editActivity = function()
	{
	  $.showLoading('Updating Activity/s');
	  var update_data_items = 'update=true';
  	var url_date_parts = $('#pp_full_res iframe').attr('src').split('/');
		var url_date_parts_size = url_date_parts.length;
		$('#pp_full_res iframe').contents().find('.calendar_widget').each(function(i){
			var input_element_id_parts = $('.inputs span:visible input', this).attr('id').split('_');
  		var unit_type_id = input_element_id_parts[2];
  		// convert the intensity scale id to real values
  		var intensity_scale_id = $('input.amount2.inputB', this).val().split('%');
  		var intensity = $.convertIntensity(intensity_scale_id[0]);
  		update_data_items += '&activities[' + i + '][ActivityID]='+$('input[name=activity_id]', this).val();
  		update_data_items += '&activities[' + i + '][ActivityValue]='+$('.inputs span:visible input', this).val();
  		update_data_items += '&activities[' + i + '][UnitTypeID]='+unit_type_id;
  		update_data_items += '&activities[' + i + '][IntensityScaleID]='+intensity;
  		update_data_items += '&activities[' + i + '][ConversionUnitTypeID]='+$('input[name=conversion_unit_type_id]', this).val();
  		update_data_items += '&activities[' + i + '][ConversionFactor]='+$('input[name=conversion_factor]', this).val();
    });
		$.post('/calendar/update', update_data_items, function(xml){
    	$.showLoading('Refreshing Calendar');
	    $.get('/calendar/' + url_date_parts[url_date_parts_size-3] + '/' + url_date_parts[url_date_parts_size-2], $.updateCalendar);
    });
    return false;
	}

	jQuery.updateCalendar = function(xml)
	{
    $.hideLoading();
    $('#mainGrid').slideUp('slow', function(){
      $('#activityCalendar').html(xml);
      $('#mainGrid').slideDown('slow');
      $.calendarAttachBehaviors();

    });
	}

	jQuery.showLoading = function(message)
	{
		$('#monthWrap').find('.indicator span').text(message).end().find('.indicator').show();
		$('html,body').attr({scrollTop: $('#activityCalendar').offset().top});
	}

  jQuery.hideLoading = function()
  {
    $('#monthWrap .indicator').hide();
  }

	jQuery.convertIntensity = function(percentage)
	{
		percentage = parseInt(percentage);
		if(percentage > 0 &&  percentage <= 20) return 6;
		else if(percentage > 20 &&  percentage <= 25) return 7;
		else if(percentage > 25 &&  percentage <= 30) return 8;
		else if(percentage > 30 &&  percentage <= 35) return 10;
		else if(percentage > 35 &&  percentage <= 40) return 11;
		else if(percentage > 40 &&  percentage <= 45) return 12;
	  else if(percentage > 45 &&  percentage <= 50) return 13;
		else if(percentage > 50 &&  percentage <= 60) return 14;
		else if(percentage > 60 &&  percentage <= 70) return 15;
		else if(percentage > 70 &&  percentage <= 75) return 16;
		else if(percentage > 75 &&  percentage <= 80) return 17;
		else if(percentage > 80 &&  percentage <= 90) return 18;
		else if(percentage > 90 &&  percentage <= 100) return 19;
		else if(percentage > 100) return 20;
		else return 6;
	}

	jQuery.loadAndAttachDatePickers = function()
	{
		// jquery calendar for the reporting date selectors
    $.getScript("/js/jquery-ui-1.7.custom.min.js", function(){
      $('input.datepicker').datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'dd-mm-yy',
        yearRange: '2009:2010',
        defaultDate: '-7d'
      });
    });
	}

	jQuery.loadAndAttachPrettyPhoto = function()
	{
            //$("a[rel^='prettyPhoto']").unbind();
           // $("a[rel^='prettyPhoto']").prettyPhoto();
	}
