/*jslint browser:true */
/*global $, $$*/

function getBrowserWidth(){
if(window.innerWidth){return window.innerWidth}
else{
 if(document.documentElement&&document.documentElement.clientWidth!=0){
    return document.documentElement.clientWidth 
 }
 else{
  if(document.body){return document.body.clientWidth}
 }
}
return 0 
}


// responsiveImageTag detects all noscript elements on the page with a class 
// of 'responsivize'.

// It retrieves both HTML5 data attributes and then creates an image tag with
// the correct source destination depending on the available screen width of 
// the user's device. This way smaller images are sent to mobile devices or
// any device smaller than 768px. 

// The <noscript> tags are then removed from the page.
var responsiveImageTag = {

/*
    getBrowserWidth:function(){
		if(window.innerWidth){return window.innerWidth}
		else{
		 if(document.documentElement&&document.documentElement.clientWidth!=0){
		    return document.documentElement.clientWidth
		 }
		 else{
		  if(document.body){return document.body.clientWidth}
		 }
		}
	return 0
    },
*/
	
    replaceInitialImages:function() {
		var platform = "desktop";
		var responsiveImages = $$(".responsivize");
		var i, 
			noOfresponsiveImages = responsiveImages.length;

		// Test for available width in current browser window
		// 767px, anything smaller than an ipad is considered mobile 
/*
		if(screen.width <= 767){ 
			platform = "mobile";
		}
*/
		if(getBrowserWidth() <= 499){
			platform = "mobile";
		}

		// Set initial source element on image
		for(i = 0; i < noOfresponsiveImages; i = i + 1 ){
			var noScriptElem = responsiveImages[i];
			var img = window.document.createElement("img");

			img.alt = noScriptElem.getAttribute("data-alttext");

			if(platform === "mobile"){
				img.src = noScriptElem.getAttribute("data-mobilesrc");
			}else{
				img.src = noScriptElem.getAttribute("data-fullsrc");
			}

			img.className = "responsive";
			noScriptElem.previous().appendChild(img);	
			noScriptElem.style.display = "none";
		}
    }
};

document.observe("dom:loaded", function() {
	responsiveImageTag.replaceInitialImages();
});


