$().ready(function(){
	var time = new Date();
	var timestamp = time.getTime();
	var lat =  $.cookie('lat');
	var lng = $.cookie('lng');

	var latlngurl = 'getLocation.php?' + timestamp + Math.random();
	var postcommenturl = 'saveMessage.php';
	var getcommenturl = 'jsonMessages.php';

	//defaults to delhi in case of failure
	var latlng = new google.maps.LatLng(28.6353,77.2250);

	if(lat&&lng){
		latlng = new google.maps.LatLng(lat,lng);
	} else {
		$.getJSON(latlngurl,function(data){
			if(data.lat && data.lon){
				latlng = new google.maps.LatLng(data.lat,data.lon);
				lat = data.lat;
				lng = data.lon; 
				$.cookie('lat',data.lat);
				$.cookie('lng',data.lon);
			}
		});
	}

    var mapOptions = {
      zoom: 2,
	  mapTypeControl: false,
	  scaleControl: false,
	  navigationControl: false,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map"), mapOptions);

	var inter_id;
	var inter_len = 10000; //in ms
	var json;
	var n_messages = 0;
	var rotate_index = 0;
	var info_window = new google.maps.InfoWindow();

	//start when the map is loaded
	//fetch the messages, set the timer
	google.maps.event.addListener(map, 'tilesloaded', function(){
		fetchMessages();
		google.maps.event.clearListeners(map,'tilesloaded');
	});


	function rotateInfoWindow(){
		if (n_messages) {
			var content = "<dl id='map-message'><dt>" + json.messages[rotate_index].name + "</dt><dd>" + json.messages[rotate_index].message + "</dd></dl>";
			info_window.setContent(content);
			info_window.setPosition(json.messages[rotate_index].latlng);
			map.panTo(json.messages[rotate_index].latlng);
			info_window.open(map);

			if (++rotate_index >= n_messages) {
				rotate_index = 0;
				fetchMessages();
			}
		}
	}

	function fetchMessages(){
		//reset number of messages and fetch more
		n_messages = 0;
		$.getJSON(getcommenturl,function(data){
			if(data.messages){
				json = data;
				for ( var i in json.messages) {
					json.messages[i].latlng = new google.maps.LatLng(json.messages[i].lat,json.messages[i].lon)
				}
				n_messages = json.messages.length;

				if(inter_id){
					//resetting the rotation of messages
					clearInterval(inter_id);
				}
				inter_id = setInterval(rotateInfoWindow,inter_len);
			}
		});
	}

	//pledge form submit
	$('#pledge').submit(function(){
		var author = $.trim($('#pledgeauthor').val());
		var message = $.trim($('#pledgemsg').val());

		//author latlng to be determined by server
		if(author && message && (author.length < 63) && (message.length < 140)){
			clearInterval(inter_id);
			info_window.setContent("<dl id='map-message'><dt>"+author+"</dt><dd>"+message+"</dd></dl>");
			info_window.setPosition(latlng);
			info_window.open(map);
			inter_id = setInterval(rotateInfoWindow,inter_len);


			sendToActionScript(++holding_hands_value, 'load');

			$.post(postcommenturl,{'name':author,'message':message,'lat':lat,'lon':lng});
			$('#pledgemsg').val('');
			$('#pledgeauthor').val('');
		}
		return false;
	});

	$('#imagelist').mbScrollable({
		width : 646,
		elementMargin: 0,
		elementsInPage: 1,
		height: 281,
		controls: '#pagination',
		autoScroll: false
	});

    $('#silencelist').show();
    $("#silencelist").jcarousel({
        auto: 5,
        scroll: 1,
        visible: 3,
        initCallback: silence_init,
        buttonNextHTML: null,
        buttonPrevHTML: null,
        wrap: 'both'
    });



	$("#videolist").css('display','block');

	$("#videolist").jcarousel({
        scroll: 1,
				visible: 3,
        initCallback: carousel_init,
        buttonNextHTML: null,
        buttonPrevHTML: null,
				vertical: true,
				itemVisibleInCallback: carousel_item
    });

	$('#videolist a').click(function(){
    $('#videolist img.selected').removeClass('selected');
    $(this).children('img').addClass('selected');
		$('#videoframe').attr('src',$(this).attr('href'));
		$('#videotext').text($(this).children('img').attr('alt'));
		return false;
	});


	function thisMovie(movieName) {
		if (navigator.appName.indexOf("Microsoft") != -1) {
				return window[movieName];
		} else {
				return document[movieName];
		}
	}

	function sendToActionScript(value, action) {
			thisMovie("holding_hands").sendToActionScript(value, action);
	}

	$('#videolist a:eq(0)').children('img').addClass('selected');

	sendToActionScript(holding_hands_value, '');

});

function carousel_init(carousel) {
	$('#next-video').bind('click', function() {
			carousel.next();
			return false;
	});
	$('#prev-video').bind('click', function() {
			carousel.prev();
			return false;
	});
}


function carousel_item(carousel,li,index,state){
  switch(state){
  case 'init':
    if(index == 1){
      $('#prev-video').addClass('disabled');
    }
    if(index == carousel.options.size){
      $('#next-video').addClass('disabled');
    }
    break;
  case 'next':
    if($('#prev-video').hasClass('disabled')){
      $('#prev-video').removeClass('disabled');
    }
    if(index == carousel.options.size){
      $('#next-video').addClass('disabled');
    }
    break;
  case 'prev':
    if(index == 1){
      $('#prev-video').addClass('disabled');
    }
    if($('#next-video').hasClass('disabled')){
      $('#next-video').removeClass('disabled');
    }
    break;
  }
}

function silence_init(carousel, state) {
	carousel.startAuto();
  $('#silenceplay').hide();
  $('#silencerewind').bind('click', function() {
      carousel.prev();
      carousel.startAuto(0);
      $('#silencepause').hide();
      $('#silenceplay').show();

      return false;
	});
	$('#silenceforward').bind('click', function() {
      carousel.next();
      carousel.startAuto(0);
      $('#silencepause').hide();
      $('#silenceplay').show();
			return false;
	});
  $('#silenceplay').bind('click', function(){
      carousel.startAuto(5);
      $('#silencepause').show();
      $(this).hide();
      return false;
  });
  $('#silencepause').bind('click', function(){
      carousel.startAuto(0);
      $('#silenceplay').show();
      $(this).hide();
      return false;
  });
}
