/***********************************************************************************************************

		Dominion

		This page was created by Mark R Glover for the Dominion CMS

		Name:			js_controller.js
		Info:			Javascript Controller for Dominion
		Architect:		Mark R Glover (http://www.markglover.co.uk)
		Date:			June 2011
		Status:			Active

		This page and all related content and scripts are Copyrighted.

		Copyright Mark R Glover 2011

**************************************************************************************************************/

/***************
   Functions
***************/

// Process Form
function processForm() {
	if (validateForm() == true) {
		if ($(":file").val()) {
			$("input:file").die("change", addFiles);
			$("input:file").remove();
			$("iframe").remove();
			images = 1;
		}
		action = $("form").attr("action");
		var type = $("form").attr("method");
		var data = $("form").serialize();
		$.ajax({url: action,data: data,type: type, success: function(statusText){
				statusText = statusText.split("&&&");
				if (statusText[0].search("KILL") != -1) {
					exit();
				}
				if (statusText[0].search("http:") == 0) {
				redirect(statusText[0]);
			} else {
				$("#msg").css({"background-color":"#FFFF73","border-color":"yellow"});
				$("#msg").text(statusText[0]);
				$('#msg').slideDown("normal");
				var t=setTimeout(hideMessage,2000);
				if (statusText[1]) {
					url = statusText[1];
					var q=setTimeout('redirect(url)',2000);
				} else {
					if (images == 1) {
						var t=setTimeout(reloadContent,3000);
					}
				}
		}
		}, error: function(code, text, message){
			if (message.search("KILL") == 0) {
				exit();
			}
			$("#msg").css({"background-color":"#FF7373","border-color":"#FF0000"});
			$("#msg").text(message);
			$('#msg').slideDown("normal");
			var t=setTimeout(hideMessage,5000);
		}});
	return false;
	} else {
		return false;
	}
}

function reloadContent(){
	action = action.replace("&process=true", "");
	if ($("#loading").length <= 0) {
		$("body").append("<iframe id='loading' style='display: none;'></div>");
	}
	tab = $("#tabs li.selected").attr("href");
	$("#loading").load(action, function(response,status,xhr){
		if (status == "success") {
			$("#admin_panel").replaceWith($("#loading #admin_panel"));
			var wait = setTimeout('$("#tabs li").removeClass("selected");$("[href='+tab+']").addClass("selected");$("#tabs-1").hide();$("'+tab+'").show();$("#loading").remove();', 0);
		}
	});
}

// Validate Form
function validateForm(){
	fail = false;
	count = $(".mandetory").length;
	for (i = 0; i <= count; i++) {
		if($(".mandetory:eq("+i+") :input, .mandetory:eq("+i+") textarea").val() == "") {
			$(".mandetory:eq("+i+") td:last div").remove();
			$(".mandetory:eq("+i+") td:last").append("<div style='color: #FF0000; font-weight: bold;'>This field is Mandetory</div>");
			$(".mandetory:eq("+i+")").addClass("validate");
			fail = true;
		} else {
			$(".mandetory:eq("+i+") td:last div").remove();
			$(".mandetory:eq("+i+")").removeClass("validate");
		}
	}
	if (fail == true) {
		return false;
	} else {
		return true;
	}
}

function deleteForm() {
	action = $(this).attr("href");
		$.ajax({url: action, success: function(statusText){
				statusText = statusText.split("&&&");
				if (statusText[0].search("http:") != -1) {
				redirect(statusText[0]);
			} else {
				$("#msg").css({"background-color":"#FFFF73","border-color":"yellow"});
				$("#msg").text(statusText[0]);
				$('#msg').slideDown("normal");
				var t=setTimeout(hideMessage,2000);
				if (statusText[1]) {
					url = statusText[1];
					var q=setTimeout('redirect(url)',2000);
				}
		}
		}, error: function(code, text, message){
			message = message.split("&&&");
			if (message[0].search("http:") != -1) {
				redirect(message[0]);
			} else {
			$("#msg").css({"background-color":"#FF7373","border-color":"#FF0000"});
			$("#msg").text(message[0]);
			$('#msg').slideDown("normal");
			var t=setTimeout(hideMessage,5000);
			if (message[1]) {
					url = message[1];
					var q=setTimeout('redirect(url)',5000);
				}
			}
		}});
	return false;
}

// Redirect
function redirect(url) {
	window.location = url;
}

// Hide Notification Message
function hideMessage() {
	$("#msg").slideUp("slow");
}

// Tab switching
function tabs() {
	$("#tabs li").removeClass("selected");
	$(this).addClass("selected");
	var tab = $(this).attr("href");
	$(".tab").hide();
	$(tab).show();	
}

var geocoder;
var map;
var zoomValue;
   function initialize(zoomValue) {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(53.800651,-4.064941);
    var myOptions = {
      zoom: zoomValue,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  }

  function codeAddress() {
	  initialize(18);
    var address = $("[name='pty_address']").val();
    geocoder.geocode( { 'address': address, 'region': 'UK'}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }

  function addFiles() {
      id = $(this).attr("id");
      name = $(this).attr("name");
     input = document.getElementById(id);
     $(this).wrap("<form style='display: none;' name='form_"+id+"' action='' method='post' enctype='multipart/form-data'></form>");
     $("body").append("<iframe name='upload_"+id+"' style='display: none;'></iframe>");
     action = $("form").attr("action");
	$("[name='form_"+id+"']").attr("action", action+"&image=true");
     $("[name='form_"+id+"']").attr("target", "upload_"+id);
     $("[name='form_"+id+"']").submit();
     label =  $("input:submit").val();
     $("input:submit").addClass("new-button");
     $("input:submit").val("Processing Images...");
     $("input:submit").attr("disabled", "disabled");
     $("[name='upload_"+id+"']").load(function() {
	     $("input:submit").removeClass("new-button");
	     if (label == "Processing...") {
		     label = "Save";
	     }
	     $("input:submit").val(label);
	     $("input:submit").removeAttr("disabled");
     });
     $("[name='form_"+id+"']").after("<input type='file' name='"+name+"' id='"+id+"_1' multiple/>");
     if ($("#fileList").length <= 0) {
	     $("[name='form_"+id+"']").parent().append("<ul id='fileList'></ul>");
     }
     for (i=0; i<=input.files.length; i++) {
	     $("#fileList").append("<li>"+input.files[i].name+"</li>");
     }

  }

  function saveForm() {
       timeout = "complete";
		action = $("form").attr("action");
		var type = $("form").attr("method");
		var data = $("form").serialize();
		$.ajax({url: action,data: data,type: type, success: function(){
				$("#msg").css({"background-color":"#FFFF73","border-color":"yellow"});
				$("#msg").text("Saved");
				$('#msg').slideDown("normal");
				var t=setTimeout(hideMessage,2000);
		}, error: function(code, text, message){
			message = message.split("&&&");
			$("#msg").css({"background-color":"#FF7373","border-color":"#FF0000"});
			$("#msg").text(message[0]);
			$('#msg').slideDown("normal");
			var t=setTimeout(hideMessage,5000);
		}});
	$("textarea").keyup(function(){
		if(timeout == "complete") {
			timeout = setTimeout(saveForm,120000);
		}
	});
	return false;
}

function enlargeImage(){
	  image = $(this).attr("href");
	  caption = $(this).attr("alt");
	  $("#display-gallery").append("<div id='blackout'></div>");
	  width = $(window).width();
	  height = $(window).height();
	  img_width = Math.round(width*0.9);
	  img_height = Math.round(height*0.9);
	  mag_height = height-img_height;
	  mag_height = mag_height/3;
	  $("#blackout").append("<div><img id='theImage' src='"+image+"' /><div id='caption'>"+caption+"</div></div>");
	  $("#theImage").css({"max-width":img_width,"max-height":img_height,"margin-top":mag_height});
	  $('#blackout').show(0);
	  $("#largeImage").click(restoreImage);
	  $("#blackout").click(restoreImage);
	  return false;
  }

  function restoreImage() {
	  $("#blackout").remove();
  }
  
  function slideImage() {
	  slideTime = sliderTime/2;
	  $(".sliderImage:eq("+a+")").animate({width: "0px"}, slideTime);
	  $(".sliderImage:eq("+b+")").animate({width: sliderWidth}, slideTime);
	  a = b;
	  b++;
	  c = $(".sliderImage").length-1;
	  if (a == c) {
		  b= 0;
	  }
	  sliderTimer();
  }
  
  function slideSelecterForward() {
	  slideTime = 500;
	  $(".selecterImage:eq("+d+")").animate({width: "0px"}, slideTime);
	  $(".selecterImage:eq("+d+")").css({margin: "0"});
	  $(".selecterImage:eq("+e+")").animate({width: "135px"}, slideTime);
	  $(".selecterImage:eq("+e+")").css({margin: "0 2px"});
	  d++;
	  e++;
	  f = $(".selecterImage").length-3;
	  if (d == f) {
		$(".selecterActive").animate({width: "135px"}, slideTime);
		$(".selecterActive").css({margin: "0 2px"});
		$(".selecterImage:not(.selecterActive)").animate({width: "0px"}, slideTime);
		$(".selecterImage:not(.selecterActive)").css({margin: "0px"});
		d = 0;
		e = 4;
	  }
  }
  
  function slideSelecterBackwards() {
	  slideTime = 500;
	  f = $(".selecterImage").length-1;
	  if (d == 0) {
		d = f;
		e = 3;
		$(".selecterActive").animate({width: "0px"}, slideTime);
		$(".selecterActive").css({margin: "0"});
		$(".selecterImage:eq("+d+")").animate({width: "135px"}, slideTime);
		$(".selecterImage:eq("+d+")").css({margin: "0 2px"});
		d--;
		$(".selecterImage:eq("+d+")").animate({width: "135px"}, slideTime);
		$(".selecterImage:eq("+d+")").css({margin: "0 2px"});
		d--;
		$(".selecterImage:eq("+d+")").animate({width: "135px"}, slideTime);
		$(".selecterImage:eq("+d+")").css({margin: "0 2px"});
		d--;
		$(".selecterImage:eq("+d+")").animate({width: "135px"}, slideTime);
		$(".selecterImage:eq("+d+")").css({margin: "0 2px"});
		e = f+1;
	  } else {
		  d--;
		  e--;
		  $(".selecterImage:eq("+e+")").animate({width: "0px"}, slideTime);
		  $(".selecterImage:eq("+e+")").css({margin: "0"});
		  $(".selecterImage:eq("+d+")").animate({width: "135px"}, slideTime);
		  $(".selecterImage:eq("+d+")").css({margin: "0 2px"});
	  }
  }
  
  function chooseImage() {
	  
	  clearTimeout(time);
	  $(".selecterImage,.sliderImage").stop(true);
	  b = $(this).index();
	  $(".sliderImage").animate({width: "0px"});
	  $(".sliderImage:eq("+b+")").animate({width: sliderWidth});
	  time = setTimeout(slideImage, 6000);
	  
  }
  
  function sliderTimer(){
	
	time = setTimeout(slideImage, sliderTime);
  }
  
  function faderTimer() {
      tt=setTimeout(fadeImage,sliderTime);
}

function startFadeImage() {
       for (i = 1; i<= fIa; i=i+1) {
	       x=$(".sliderImage:eq("+i+")").detach();
		$("#sliderShell").prepend(x);
       }
       faderTimer();
}

function fadeImage() {
	  slideTime = sliderTime/2;
	  $(".sliderImage:eq("+fIa+")").fadeOut(slideTime, function(){
		  x=$(".sliderImage:eq("+fIa+")").detach();
		  $("#sliderShell").prepend(x);
		  $(".sliderImage").css("display", "block");
		  faderTimer();
	  });
  }
  
  function chooseFaderImage() {
	  clearTimeout(tt);
	  $(".selecterImage,.sliderImage").stop(true);
	  b = $(this).index();
	  $(".sliderImage").hide();
	$("#"+b).fadeIn();
	  
  }

function textFader() {
	clearTimeout(tFader);
	  $(".testimonial-shell:eq("+tFa+")").fadeOut(tFadeTime,function(){ 
		$(".testimonial-shell:eq("+tFb+")").fadeIn(tFadeTime, function(){
			tFa = tFb;
			  tFb++;
			  tFc = $(".testimonial-shell").length-1;
			  if (tFa == tFc) {
				  tFb= 0;
			  }
			  tFader = setTimeout(textFader, tFaderTimer);
		});
	  });

}




/**************
  Controller
**************/
$(document).ready(function(){
	
	$("table#gallery input").change(function() {
			images = 1;
		});
	$("input:file").live("change", addFiles);
	$(":submit:not([name='noprocess'])").click(processForm);
	$("#delete-button").click(deleteForm);
	$(".delete").click(deleteForm);
	$(".delete-no-icon").click(deleteForm);
	
	
//	$("#tabs li").click(tabs);
//	$("#tabs-1").show();
//	$("#tabs li:first").addClass("selected");
//	
//	$("#map_canvas").ready(function(){
//		var address = $("[name='pty_address']").val()
//		if (address == "") {
//			initialize(5);
//		} else {
//			codeAddress();
//		}
//	});
//	$("[href='#tabs-1'],[href='#tabs-2'], [href='#tabs-3'], [href='#tabs-4'],[href='#tabs-5'],[href='#tabs-6']").click(function(){
//		var address = $("[name='pty_address']").val()
//		if (address == "") {
//			initialize(5);
//		} else {
//			codeAddress();
//		}
//	});
//	$("[name='pty_processAddress']").click(codeAddress);


//	$("#display-gallery a").click(enlargeImage);
	
	
//	a = 0;
//	b = 1;
//	d = 0;
//	e = 4;
	
	
//	$("#speed").toggle(function(){
//		$("#speed").text("Fast");
//			sliderTime = 2000;
//		}, function() {
//			$("#speed").text("Slow");
//			sliderTime = 5000;
//
//	});


//	$("#forward").click(slideSelecterForward);
//	$("#back").click(slideSelecterBackwards);
//	$(".selecterImage").click(chooseImage);
//	sliderTime = 5000;
	
	
//	if (sliderWidth) {
//		time = setTimeout(slideImage, sliderTime);
//	}


//	if (faderWidth) {
//		tFader = setTimeout(textFader, 5000);
//	}
});
