/**
 * @product     opus-fashion.com
 * @file        /public/js/script.js
 * @copyright   (c) 2010 mukutu GmbH (http://www.mukutu.de)       
 */

//TODO: get these Variables from Application
var lang = 'de'; 
var productImagesPath = 'data/productimages/'; 

dojo.require("dojo.fx");

dojo.addOnLoad(function() {
//	if(dojo.byId("newShippingAddress")!=null) {
//		//load all widget functions
//		chooseNewAddress();
//	}	
	if(dojo.byId("widget_login")!=null) {
		//load all widget functions
		loginDiv();
		cartanimation();
	}	
	if(dojo.byId("allSizes-element")!=null) {
		addtocart();
	}
	if(dojo.byId("zoomimage")!=null) {
		mag();
	}
});

function strReplace(search, replace, subject) {
	return subject.split(search).join(replace);
	}

function chooseNewAddress() {
	dojo.connect(dojo.byId("newAddress-firstname"), "onfocus", function(event) {
		checkNewAddress();
	});
}

function checkNewAddress() {
	console.log("checkNewAddress");
	//TODO: check the last checkbox, uncheck all others
//	dojo.byId("address-shippingaddress-9999999").setAttribute('checked', 'checked');
//		if(!radioObj)
//			return;
//		var radioLength = radioObj.length;
//		if(radioLength == undefined) {
//			radioObj.checked = (radioObj.value == newValue.toString());
//			return;
//		}
//		for(var i = 0; i < radioLength; i++) {
//			radioObj[i].checked = false;
//			if(radioObj[i].value == newValue.toString()) {
//				radioObj[i].checked = true;
//			}
//		}
//	}
}

//----------------------- imageswitch -------------------------------\\
function switchImage(src) {
	dojo.byId("productimage").src = src.replace(/67x85/i, "268x342");
	dojo.byId("zoomimage").style.overflow = "";
	dojo.byId("zoomimage").style.backgroundPosition = "center";
	dojo.byId("zoomimage").style.backgroundImage = "url(/images/loading.gif)";
}


//----------------------- image magnifier ----------------------------\\
function mag() {
	dojo.connect(dojo.byId("productimage"), "onmouseover", function(event) {
		dojo.byId("productdetail").style.display = "none";
		dojo.byId("zoomimage").style.display = "";
	});
	dojo.connect(dojo.byId("productimage"), "onmouseout", function(event) {
		dojo.byId("zoomimage").style.display = "none";
		dojo.byId("productdetail").style.display = "";
		dojo.byId("zoomimage").style.overflow = "";
	});
	dojo.connect(dojo.byId("productimage"), "onmousemove", function(event) {
		if (typeof event == 'undefined') {
			evt = window.event;
		} else {
			evt = event;
		}
		obj = dojo.byId("productimage");
		src = obj.src;
		imgZoom = new Image();
		imgZoom.src = src.replace(/268x342/i, "1450x1850");
		if(imgZoom.complete) {
			var topValue=0;
			var leftValue=0;
		    while(obj){
		    	leftValue += obj.offsetLeft;
		    	topValue += obj.offsetTop;
		    	obj = obj.offsetParent;
		    }
		    var x = (evt.clientX-leftValue)*5.4;
		    var y = (evt.clientY-topValue)*5.4;
		    imgUrl = dojo.byId("zoomimage").style.backgroundImage.split('"')[1];
		    if(imgUrl != imgZoom.src ) {
		    	console.log('image replaced');
		    	dojo.byId("zoomimage").style.overflow = "auto";
		    	dojo.byId("zoomimage").style.backgroundImage = "url("+imgZoom.src+")";
		    }
		    dojo.byId("zoomimage").style.backgroundPosition = "-"+x+"px -"+y+"px";
		}
	});
}

function showmag(v) {
	if(v) {
		dojo.byId("productdetail").style.display = "none";
		dojo.byId("zoomimage").style.display = "";
	} else {
		dojo.byId("zoomimage").style.display = "none";
		dojo.byId("productdetail").style.display = "";
	}
}

//----------------------- functions for widgets -----------------------\\

function loginDiv() {
	dojo.connect(dojo.byId("menu-login"), "onclick", function(event) {
		if(dojo.byId("widget_login").style.display=='none') {
			dojo.byId("widget_login").style.display='';
		} else {
			dojo.byId("widget_login").style.display='none';
		}
	});
}

function cartanimation() { 
	dojo.connect(dojo.byId("menu-cart"), "onclick", function(event){
		dojo.byId("menu-cart").blur();
		event.preventDefault();
		event.stopPropagation();
		if(dojo.byId("widget_cart").style.display=='none') {
			updateFloatProducts();
			updateSum();
			doAnimation(1);
		} else {
			doAnimation(2);
		};
	});
}

function updatecart() {
	updateFloatProducts();
	doAnimation(1);
	var xhrArgs = {
		url: "/"+lang+"/shop_cartajax/getsum",
	    handleAs: "json",
	    load: function(data) {
			var text = dojo.byId("menu-cart").innerHTML;
			textArray = text.split("|");
			var pieces = data["pieces"];
			if(pieces<10) {
				pieces = '0'+pieces;
			};
			textArray[1] = textArray[1].replace(new RegExp(/\d+/), pieces);
			textArray[2] = textArray[2].replace(new RegExp(/[0-9]+[,.][0-9][0-9]/), data["price"].replace('.',','));
			text = textArray.join("|");
			dojo.byId("menu-cart").innerHTML = text;
			updateSum();
		},
	    error: function(error) {
			targetNode.innerHTML = "An unexpected error occurred: " + error;
        }
	};
	//Call the asynchronous xhrGet
	var deferred = dojo.xhrGet(xhrArgs);
	setTimeout(function(){doAnimation(2);}, 1000);
}

function updateSum() {
	var text = dojo.byId("menu-cart").innerHTML;
	textArray = text.split("|");
	dojo.byId("floatsumcart").innerHTML = textArray[2]; 
}

function doAnimation(index) {
	duration = 500;
	var currentAnimation;
    switch(index) {
      case 1:
    	currentAnimation = dojo.fx.wipeIn({node: "widget_cart", duration: duration});
        break;
      case 2:
    	currentAnimation = dojo.fx.wipeOut({node: "widget_cart", duration: duration});
        break;
      case 3:
        currentAnimation = dojo.fx.chain([dojo.fx.wipeIn({node: "widget_cart",duration: duration}), dojo.fx.wipeOut({node: "widget_cart",duration: duration})]);
        break;
    }
    //Play the animation. Without this call, it will not run
    currentAnimation.play();
}

function addtocart() {
	//replaces normal submit with the ajaxform
	detailform = dojo.byId("productdetail");
	dojo.connect(detailform, "onsubmit", function(e){
		e.preventDefault();
		console.log(dojo.byId("shoppingcart"), 'cart'); //.attr('disabled', true);
		dojo.byId("shoppingcart").disabled = true;
		var xhrArgs = {
			url: "/"+lang+"/shop_cartajax/add",        		
			form: dojo.byId("productdetail"),
			handleAs: "text",
			sync: true,
			preventCache: true,
			load: function(data) {
				console.log("data: "+data);
				if(data!=1) {
					alert(data);
					return false;
				}
				updatecart();
				return true;
			},
			error: function(error) {
				return error;
				console.log("error: "+error);
			}
		};
		//Call the asynchronous xhrPost
		var deferred = dojo.xhrPost(xhrArgs);
		setTimeout(function(){dojo.byId("shoppingcart").disabled = false;}, 1000);
//		setTimeout(function(){dijit.byId("shoppingcart").attr('disabled', false);}, 1000);
	});
}

function updateFloatProducts() {
	var xhrArgs = {
		url: "/"+lang+"/shop_cartajax/getfloatcartproducts",
		handleAs: "text",
		sync: true,
		preventCache: true,
		load: function(data) {
			console.log("data: "+data);
			showFloatProducts(data);
		},
		error: function (error) {
			console.log("error: "+error);
		}
	}
	var deferred = dojo.xhrPost(xhrArgs);
}

function updateFloatSum() {
	
}

function showFloatProducts(data) {
	data = dojo.fromJson(data);
	dojo.byId("widget_cart_products").innerHTML = "";
	var div = dojo.create("div");
	if(data.length<1) {
		var list = dojo.create("ul", {"class": "v_13"});
		var text = dojo.create("li", {innerHTML: "Ihr Warenkorb enthält noch keine Artikel"});
		list.appendChild(text);
		div.appendChild(list);
	}
	dojo.forEach(data, function(item, i) {
		var list = dojo.create("ul", {"class": "v_13"});
		var color = item['color_code'];
		if(color<10)
			color = "00"+color;
		if(color<100)
			color = "0"+color;
		var image = dojo.create("img", {src: "/"+productImagesPath+"67x85/"+item['model_code']+"_"+color+".jpg", alt: ""}); //TODO: Bildpfad anpassen!
		
		var imagelink = dojo.create("a", {"href": "/"+lang+"/shop_detail/index/id/"+item['model_code']+"/color/"+color});
		imagelink.appendChild(image);
		
		var imagecontainer = dojo.create("li", {"class": "img"});
		imagecontainer.appendChild(imagelink);
		
		list.appendChild(imagecontainer);
		var name = dojo.create("li", {innerHTML: item['model_name']});
		list.appendChild(name);
		var code = dojo.create("li", {innerHTML: "Art.-Nr.: "+item['model_code']}); //TODO: translate
		list.appendChild(code);
		var price = dojo.create("li", {innerHTML: strReplace('.', ',', item['price'])+' €'}); //TODO: Formatierung mit Zend_Currency
		list.appendChild(price);
		var color = dojo.create("li", {innerHTML: "Farbe: "+item['color_name']}); //TODO: translate
		list.appendChild(color);
		var size = dojo.create("li", {innerHTML: "Größe: "+item['size']}); //TODO: translate
		list.appendChild(size);
		var quantity = dojo.create("li", {innerHTML: "Anzahl: "+item['quantity']}); //TODO: translate
		list.appendChild(quantity);
		div.appendChild(list);
	});
	dojo.byId("widget_cart_products").appendChild(div);	
}