/*
 * AusRAP
 *
 * Copyright (c) 2011 Involved Pty. Ltd.
 */


/*
 * jQuery DOM ready handler
 */
$(document).ready(function(){
	Ausrap.init();
});


/*
 * Browser resize handler
 */
$(window).resize(function(){

});

var Ausrap = function(){

  function init(){
    initTweets();
    initQuestionForm();
    initLightbox();
    
    var bodyId = $('body').attr('id');
    switch(bodyId){
      case 'decade-of-action':
        initCarousel();
        break;
      case 'star-ratings':
        initMap();
        break;
      case 'faqs':
        initFaqs();
    }
    
    var bodyClass = $('body').attr('class');
    switch(bodyClass){
      case 'ratings':
        initTabs();
        initActiveTab();
        break;
    }
    
  }

  function initTweets(){
    $("#tweets").tweet({
      username: "aaaausrap",
      count: 1,
      loading_text: "Loading tweets...",
      template: "{text}{time}"
    });
  }
  
  function initFaqs(){
    //Slide up and down on click + change Show/Hide text
    $("dl#questions dt").click(function(){
      $(this).next("dl#questions dd").slideToggle("slow");
        if ( $(this).hasClass("active") ) {
          $(this).removeClass("active");
      } else {
        $(this).addClass("active");
      }
    });	
	
    // Hotlink FAQs
    if(document.location.hash!='') {
      //get the index from URL hash
      faqSelect = document.location.hash.substr(1,document.location.hash.length);
      var faqID = '#' + faqSelect;
      $(faqID).addClass("active");
      $(faqID).next("dl#questions dd").show();
    }  
  }
  
  function initTabs(){
    var initab = 0;
    var initab2 = 0;
    var lhash = window.location.hash;
    if (lhash) { 
      lhash.match(/^#(\d+)-(\d+)/);
      initab = RegExp.$1 - 1;
      initab2 = RegExp.$2 - 1;
    }

    $("ul.tabs").tabs("ul#maps .pane",{initialIndex:initab});
    $("ul.sub-tabs").tabs("> .sub-pane",{initialIndex:initab2});
    $("ul.tabs a, ul.sub-tabs a").click(function(){
      initActiveTab();
    });
    
    // Example deep linking - /risk-ratings-explained/#2-2
  }

  function initActiveTab(){
    $('.pane').each(function(index) {
        var active_tab = $(this).find('.sub-tabs li a.current');
        var offset = -1051;
        var tab_pos = active_tab.position();
        var tab_width = active_tab.width();

        if (tab_pos != null){
          $(this).find('.arrow').animate({ left: (offset + tab_pos.left + (tab_width/2)) }, 0 ); 
        }
    });  
  }
   
  function initCarousel(){
    $("#carousel").carouFredSel({
    	width: 980,
    	height: 310,
    	items: {
    		visible: 1,
    		minimum: 1,
    		width: 980,
    		height: 310
    	},
    	scroll: {
    		pauseOnHover: true
    	},
    	scroll: {
      	fx: "fade"
      },  
    	auto: 5000,
			pagination: {
			  container: ".pagination",
			  anchorBuilder: function(nr) {
			    return "<a>&bull;</a>";
			  }
			}
    });
  }
  
  function initLightbox(){
    $("#videos ul, a[rel^='lightbox']").ceebox({
      videoGallery: true,
      titles: true,
      videoWidth: 1000
    });
  }
  
  function initMap(){  
    	var geocoder;
    	var map;
    	// Set up a map style to make the map black and white (useful for star ratings)
    	// Refer to: http://gmaps-samples-v3.googlecode.com/svn/trunk/styledmaps/wizard/index.html

    	var mapstyle = [
    		{
    			featureType: "all",
    			elementType: "all",
    			stylers: [
    				{ saturation: -100 },
    				{ lightness: -10 },
    				{ gamma: 0.75 }
    			]
    		}
    	];

    	// Set map options
    	//		Controls: (road map, black&white, satellite, hybrid and terrain)
    	//		Zoom: 4 - change to suit (lower = further from earth)
    	var myOptions = {
    		mapTypeControlOptions: {
    			mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'blackwhite', google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.TERRAIN]
    		},
    		zoom: 4,
    		zoomControl: true,
        zoomControlOptions: {
          style: google.maps.ZoomControlStyle.SMALL
        },
    		center: new google.maps.LatLng(-27.722436,133.945313),
    		mapTypeId:  google.maps.MapTypeId.TERRAIN,
    		streetViewControl: true
    	};

    	// Load the map into the map_canvas div
    	var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    	// Associate styled map with the B&W Map control
    	var styledMapOptions = {
    		map: map,
    		name: "B&W Map"
    	};

    	var opt = {
    		mapTypeControlOptions: {
    			mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'blackwhite']
    		},
    		mapTypeId: 'blackwhite'
    	};

    	var styledMapType = new google.maps.StyledMapType(mapstyle,styledMapOptions);

    	map.mapTypes.set('blackwhite', styledMapType);

      var kmlSource = ($("#map_canvas").attr('data-kml-src') + "/").replace(/\/\/$/, "/");
      $("#map_canvas").attr('data-kmz').split(",").map(function(kmz){ new google.maps.KmlLayer(kmlSource + kmz + ".kmz", {clickable: false, preserveViewport: true, suppressInfoWindows: true}).setMap(map); });
  }
    
  function inputError(element){
    $(element).addClass("error");
    $(element).fadeTo(0, 0.1);
    $(element).delay(100).fadeTo(100, 1);
  }
  
  function initQuestionForm(){

    $('.message, .email').placeholder();

    var form = $("#contact form");
    form.find(".message").BetterGrow({
      initial_height: 60
    });

    form.find("input:submit").click(function() {
      form.find("input, textarea").removeClass("error");
      var hasError = false;
      var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
      
      var email = form.find(".email");
      var emailVal = form.find(".email").val();
      
      var message = form.find(".message");
      var messageVal = form.find(".message").val();

      if(emailReg.test(emailVal) == false || emailVal == '') {
        inputError(email);
        hasError = true;    
      }
      if(messageVal == '') {
        inputError(message);
        hasError = true;
      }

      if(hasError == false) {
        var dataString = 'emailFrom=' + emailVal + '&message=' + messageVal;  
        // console.log(dataString);
        // Submit the form via ajax
        $.ajax({
          url: form.attr('action'),
          type: "POST",
          data: dataString,
          statusCode: {
            200: function(){
              $("#contact form").fadeOut(300);
              $("#contact .confirmation").delay(300).fadeIn(500); 
              $("#contact .confirmation").tabIndex = -1;
              $("#contact .confirmation").focus(); // For screen reader accessibility
            }
          }
        });        
      }
  		return false;	
  	});
  }


  return{
    init: init
  };
}();


/* Map prototype function for IE */
if (!Array.prototype.map)
{
  Array.prototype.map = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array(len);
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        res[i] = fun.call(thisp, this[i], i, this);
    }

    return res;
  };
}




