

/* -- START /VAR/WWW/HTML/ROCKETSHOP.CO/PUBLIC_HTML/CORE/2.1.4/JS/JQUERY.COREAPP.JS ---------------------------------------------------------- */



var retries = 0;

$.fn.serializeObject = function() {
	var arrayData, objectData;
	arrayData = this.serializeArray();
	objectData = {};
  
	$.each(arrayData, function() {
		var value;
	
		if (this.value != null) { value = this.value; } else { value = ''; }
	
		if (objectData[this.name] != null) {
		  if (!objectData[this.name].push) { objectData[this.name] = [objectData[this.name]]; }
		  objectData[this.name].push(value);
		} else { objectData[this.name] = value; }
	});
  
	return objectData;
};

rot13 = function(str) {
    // Perform the rot13 transform on a string  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/str_rot13
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   bugfixed by: Onno Marsman
    // +   improved by: Rafał Kukawski (http://blog.kukawski.pl)
    return (str + '').replace(/[a-z]/gi, function (s) {
        return String.fromCharCode(s.charCodeAt(0) + (s.toLowerCase() < 'n' ? 13 : -13));
    });
}

// GOOGLE MAPS V2.0 - LOAD DYNAMICALLY - IF NEEDED ON PAGE
$.fn.core_map = function() { 
	var $c = $(this).closest(".core-map-container");

	var lat = $(".core-map-markers li:first", $c).data("lat");
	var long = $(".core-map-markers li:first", $c).data("long");
	var location = new google.maps.LatLng(lat,long);
	var myOptions = { zoom: 12, center: location, mapTypeId: google.maps.MapTypeId.ROADMAP }
	var markerpos = {};
	
	var directionsService = new google.maps.DirectionsService();
	var directionsDisplay = new google.maps.DirectionsRenderer();

	map = new google.maps.Map( $(".core-map-canvas", $c).get(0), myOptions);

	directionsDisplay.setMap(map);
	directionsDisplay.setPanel( $(".core-map-directions").get(0) );
	
	var infowindow = new google.maps.InfoWindow();
	google.maps.event.addListener(map, 'click', function() { infowindow.close(); });
	
	if(navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(function(position){
			var start = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
			var request = { origin: start, destination: location, travelMode: google.maps.DirectionsTravelMode.DRIVING };
			directionsService.route(request, function(response, status) {
			  if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); }
			});
		});
	}
	
	var i = 0; $(".core-map-markers li", $c).each(function() {
		
		var title = $(this).data("title");
		var lat = $(this).data("lat");
		var long = $(this).data("long");
		var info = $(this).html();
		markerpos[i] = new google.maps.LatLng(lat,long);
		
		var contentString = '<div id="content">'+
			'<h2 id="firstHeading" class="firstHeading">'+title+'</h2>'+'<p>'+info+'</p>'+
			'</div>';
		
		if ((lat !== "") && (long !== "")) {
			
			var MarkerImage = new google.maps.MarkerImage('http://chart.apis.google.com/chart?chst=d_map_pin_icon&chld=info|FF0000');
			var Marker = new google.maps.Marker({
				position: markerpos[i], map: map,
				icon: MarkerImage, title: title
			});
			
			google.maps.event.addListener(Marker, 'click', (function(Marker, i) {
				return function() {
				  location = markerpos[i];
				  infowindow.setContent(contentString);
				  infowindow.open(map, Marker);
				}
			})(Marker, i));
		}
		i++;
	});

	$("input#start", $c).click(function() { $(this).select(); });
	$("form", $c).submit(function() {
		var start = $("input#start", $c).val();
		var request = { origin: start, destination: location, travelMode: google.maps.DirectionsTravelMode.DRIVING };
		directionsService.route(request, function(response, status) {
		  if (status == google.maps.DirectionsStatus.OK) { 
			$("form", $c).find(".core-ajax-loading").remove();
			directionsDisplay.setDirections(response); 
		  }
		});
		return false;
		  
	});	

}
function map(){ $(".core-map-canvas:last").core_map(); }

function trans($rs){
	var $active = $(".rocketslider-reel > li.active", $rs);
	if ( $active.length == 0 ) $active = $(".rocketslider-reel > li:first", $rs);
	$next = $active.next("li").length ? $active.next("li") : $(".rocketslider-reel > li:first", $rs);
	$next.css({opacity: 0.0}).addClass('active').animate({opacity: 1.0, 'z-index': 1}, 1000, function() { $active.css({opacity: 0.0}).removeClass('active'); });
}

function tick(redir) { 
	if ( parseInt( $("#core-count-down").html() )==0) window.location = $("#core-count-down").data("href"); 
	else { $("#core-count-down").html( parseInt( $("#core-count-down").html() )-1 ); };
}

$.fn.core_activate = function(options) {
	
	var defaults = {};
	var options =  $.extend(defaults, options);  
	
	return this.each(function() {

		var o = options;
		var $context = $(this); // this should be hidden for non-js systems ...
		
		 // 404 TIMER
		 if ($("#core-count-down").length > 0) setInterval('tick()', 1000);
		
		// RUN BASIC SLIDESHOWS ON IE7 AND iE8
		$(".ie7 .rocketslider, .ie8 .rocketslider, .ie9 .rocketslider").each(function() {
			$rs = $(this); $(".rocketslider-loader", $rs).hide("slow");
			if ($rs.data("speed") == undefined) $rs.data("speed", 7000);
			$(this).data("timer", setInterval(function() { trans($rs); }, $rs.data("speed")));
		});
		

		// DYNAMICALLY LOAD GOOGLE MAPS
		if ($(".core-map-canvas").length > 0) {
			if (typeof google === 'object' && typeof google.maps === 'object') { $(".core-map-canvas").core_map(); } 
			else { $.getScript( "http://maps.google.com/maps/api/js?sensor=true&sync=2&callback=map"); }
		}
		$(".core-obfuscate", $context).each(function() { $(this).replaceWith( rot13($(this).html()) ); });

		// SUMMARY SCREEN UPDATE
		$(".core-expand-list label.core-expand").click(function() {  
			var $expandable = $(this).closest(".core-expand-list > li");
			$expandable.find(":input").each(function() {
				var v = $(this).val();
				var $i = $( ".core-summary-"+$(this).attr("id").replace(/\./gi,"-") );
				if (v == "") v = $i.data("placeholder");
				$i.html( v );
			});
		})

		// IF JS IS ENABLE SHOW LOADING BUTTON - EVEN IF AJAX ISN'T ENABLED ...
		$("form :submit", $context).unbind().click( function(e) {
			$(this).closest("form").find(".core-ajax-loading").remove();
			$(this).after( $("<div />").addClass("core-ajax-loading").html( "Working" ).css("top",0).prepend( $("<div />").addClass("core-spinner").css({"width":16,"height":16}) ) );
		});
		
		$("a[data-ajax-target], form[data-ajax-target] :submit", $context).unbind().click( function(e) {
	
			e.preventDefault();

			var data = null;
			var u = $(this).attr("href");

			// GET THE TARGET
			var targetId = "#"+$(this).data("ajax-target");
			if (u === undefined ) { // MUST BE A FORM
				var $form = $(this).closest("form");
				u = $form.attr("action");
				if (u === undefined ) u = window.location.href;
				data = $form.serializeObject();
				targetId = "#"+$form.data("ajax-target");
			}
			var $target = $( targetId );
//console.log(targetId);		

			$target.find("form:last .core-ajax-loading").remove();
			$target.find("form:last").css("position", "relative"); // make loader relative to form - remove this when done
//console.log( $target.find("form:last") );		
			$target.find("form:last").prepend( $("<div />").addClass("core-ajax-loading").html( "Working" ).css("top",0).prepend( $("<div />").addClass("core-spinner").css({"width":16,"height":16}) ) ); // just in case it's hidden core-relative
//console.log(u);		
			$.ajax({
				url: u,
				data: data,
				type: 'POST',
				cache: false,
				async: true,
				success: function(data, textStatus, jqXHR) {
	
//console.log($(data).find(targetId));
					retries = 0;
 					$replace = $(data).siblings(targetId); if ($replace.length == 0) $replace = $(data).find(targetId);
					$target.replaceWith( $replace );
					
					$new_target = $(targetId); // THIS FINDS THE NEW ELEMENT
	
//						$('html,body').animate({scrollTop: $new_target.offset().top-100},'slow'); // SCROLL TO FORM JUST REFRESHED - IF IN A LIST
					$new_target.core_activate();
					if (window.parent !== undefined) window.parent.postMessage('refresh', '*')	
					
					return $new_target;
					
				},
				statusCode: {
					403: function() {
//						var version = $(".core-content").data("version");
//						$.ajax({ url: "/"+version+"/login", success: function() { $target.core_get_content(u, o); }} ); // LOG IN THEN CALL IT
					},
					500: function() { // server error - maybe a timeout - maybe an async action in conflict with another ... retrying ...
//						o.async = false; // if there's a problem switch to synchronous
//						retries++;
//						if (retries < 3) {
//							setTimeout(function() { 
//								$target.core_get_content(u, o);
//							}, 750);
//						} else {
//							retries = 0;
//							var $parent = $target.parent();
//							$parent.find("div.core-ajax-content:first").find(".core-ajax-loading").remove();
//							$parent.prepend( $("<div />").addClass("core-flash core-flash-failure").html("There was a system fault trying to complete this action. Please take note of what you were attempting to do (including any values entered in the form) and forward the details to the system admin.") );
//						}
					}
				  }
			});		
			
		});
		
	})
	
};

$("document").ready ( function () {
	
	$("body").core_activate();
	
});




/* -- END /VAR/WWW/HTML/ROCKETSHOP.CO/PUBLIC_HTML/CORE/2.1.4/JS/JQUERY.COREAPP.JS ------------------------------------------------------------ */

