
/*
----------------- Global object containing commonoly used funcitons -----------------*/

	var g = {
		
	
	// Prenvent default action
		stopDefault: function (e) {
			if (window.event) {
				window.event.returnValue = false;
			} 
			if (e && e.preventDefault) {
				e.preventDefault();
			}
		},
	
	
	// Cross browser add event
		addEvent: function (elm, evType, fn, useCapture) {
			if (elm.addEventListener) {
				elm.addEventListener(evType, fn, useCapture);
				return true;
			} else if (elm.attachEvent) {
				var r = elm.attachEvent('on' + evType, fn);
				return r;
			} else {
				elm['on' + evType] = fn;
			}
		}
	};	


/*
-----------------   Fire Functions as soon as DOM is ready -----------------------------------*/	

	$(document).ready(function() {
		
		newWindowIcon();							/* Add new window icon to external links */
			
		$('.supp').click(function(e) {	
			var thisLink = this.href;
			window.open(thisLink, 'mypop', "height=400, width=400"); 
            g.stopDefault(e);
            return false;
		});
	
	});
		
		

//$.ajax({
  //  type: "POST",
    //url: "http://localhost:8888/jbdoors/assets/js/test.js",
    //contentType: "application/json; charset=utf-8",
    //dataType: "json",
    //success: function(json) {
      //  console.log("shoe")
		//$('#images').append(json);

/*
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 3 ) return false;
});/
	
	//,
    //error: function (XMLHttpRequest, textStatus, errorThrown) {
      //  $("#error").html(XMLHttpRequest.responseText);
    //}
});

 


	});
	


	function gallery() {
		if (!document.getElementById("thumbs") || !document.getElementById("gallery")) return false;
		var thumbs = document.getElementById("thumbs");
		var galleryContainer = document.getElementById("gallery");
			var galleryImage = document.getElementById("gallery").getElementsByTagName("img")[0];
			thumbs.onclick = function(e) {
				var t = g.getTarget(e); // delegate!!		
					var links = t.parentNode;
					g.stopDefault(links);
					galleryImage.src = links.href;
					galleryImage.id = links.id + "-dynamic";
					galleryContainer.className = "showtoggle";
					if (!document.getElementById("inventory-swap")) return false;
					var inventorySwap = document.getElementById("inventory-swap");
					inventorySwap.className = "hidetoggle";
					
					return false;			
			}
	
	}
/*
-----------------  Form Validation  -----------------------------------*/	

		
		/*------- Convert submit button to link ----------*/
			/*
			function submitButton() {
				$("form .formsubmit").each( function() {
					var currentForm = this;
					var buttonText = currentForm.value;
					$(currentForm).before('<div class="button-container fleft wbg"><a href="#">' + buttonText + '</a></div>').remove(); 
				});
			};*/

		
		/*------- Email Article Form ----------*/
			
			var articleEmailForm = {
			
				// Validation rules
				emailFormValidation: function () {
					if(!document.getElementById("survey-brochure-request")) {
						return false;
					}
					$("#survey-brochure-request").RSV({
						//onCompleteHandler: myOnComplete,
						displayType: "display-html",
						errorTextIntro: "Please correct the following errors:",
						errorFieldClass: "errorfield",
						rules: [
							"required,fullname,Enter your name",
							"required,address,Enter the first line of your address",		
							"required,postcode,Enter your name",							
							"length=7-8,postcode,Enter a valid postcode",
							"required,email,Enter an email address",
							"valid_email,email,Enter a valid email address",		
						]
					});
				}
				
				//Submit eamilarticle form
				/*
				submitEmailArticleForm: function () {
					if(!document.getElementById("article-email")) {
						return false;
					}
					$('#article-email div.js-button-container').click(function(e) {
						e.preventDefault();
						$('#article-email').submit();
					});
				}*/
			}
			
		
		


	
/*
-----------------  9. Event delegation -----------------------------------*/	

/* New window Icon */
	function newWindowIcon() {
		$("a[@rel$='external']").append(" <img src='/assets/img/misc/icon-new-window.gif' alt='(link open in new browser window)'").click(function(){
			this.target = "_blank";
		});
	}

/* ------------------ POPUPS ------------------------------------*/   
	
	


	/*
	popupClickHandler: function (e) {
        var theEvent = e || window.event;	
        var trigger = theEvent.target || theEvent.srcElement;
        var triggerParent = trigger.parentNode;
        var thisLink, uniqueLink;
*/
	// Get target href or target parent href.  This will be used to determine what page is opened
  /*
  if (trigger.nodeName.toLowerCase() === "a") {
            thisLink = trigger.href;
            uniqueLink = trigger;
        } else if (triggerParent.nodeName.toLowerCase() === "a") {
            thisLink = triggerParent.href;
            uniqueLink = triggerParent;
        } else {
            return;
        }		
	*/							
	//Standard Popups
      /*
	  if ((trigger.className && (" " + trigger.className + " ").indexOf(" popup ") !== -1) || (triggerParent.className && (" " + triggerParent.className + " ").indexOf(" popup ") !== -1)) {			
			window.open(thisLink); 
            g.stopDefault(e);
            return false;
        }
    }
};*/
// end event delegation



/*
----------------- 11. Load events on page load -----------------------------*/

 $(window).load(function () {
	articleEmailForm.emailFormValidation();
	gallerSwitch();
	//articleEmailForm.submitEmailArticleForm();
});
	

function gallerSwitch () {
	//var activeThumbSrc = $("img.activeThumb")[0].src;
	//var thumbSrc =  
	
	//alert(activeThumbSrc)
	// Add class of hidden to all the list items
	$('#doorlist > li').addClass('hidden');
	$('#door-thumbs ul li a').click( function(e) {
		e.preventDefault();
		// Get existing selected image and updated to non-selected image
			var activeThumb = $("img.activeThumb")[0];
			var activeThumbSrc = activeThumb.src;
			var originalSrc = activeThumbSrc.replace("-act", "");
			activeThumb.src = originalSrc;
			$(activeThumb).removeClass('activeThumb');
		// Get the image clicked on and add the "-act" part to the image src to appear like its selected
			var newActiveThumb = this.firstChild;
			var newActiveThumbSrc = newActiveThumb.src;
			var newSrc =  newActiveThumbSrc.replace(".jpg", "-act.jpg");
			newActiveThumb.src = newSrc;
			$(newActiveThumb).addClass('activeThumb');
		// Display main image based on users click		
			//alert(this.parentNode.href)
			var mySplitResult = this.href.split("#");
			//alert(mySplitResult[1])
			var newActive = $("#doorlist .active");
			//alert(newActive[0].id)
			$(newActive[0]).removeClass('active');
			$('#' + mySplitResult[1]).addClass('active');
	})
}
// On thumbnail click, 
// Get the href of the link
// Set the class "active" onto the element with the matching if
// Remove the class "active" from other elements

