// adesso javascript


var count = 0;
var maxcount;
var countdown;
var basketisfull = false;
var bottlearray = ''; //new Array();



function previewRecipe(){

	var theform = document.recipeform;
	theform.setAttribute("target","_blank");
	theform.mode.value = "preview";
	
	formCheck();
	
}

function submitRecipe(){
	var theform = document.recipeform;
	theform.setAttribute("target","_top");
	theform.mode.value = "";
	
	formCheck();
}


function formCheck(){
	var error="";

	if(document.getElementById('recipe_title') && !document.getElementById('recipe_title').value){
		error=error+"> You must provide a title for your recipe\n";
		document.getElementById('recipe_title').style.border="1px solid #cc0000";
	}
	if(document.getElementById('recipe_instructions') && !document.getElementById('recipe_instructions').value){
		document.getElementById('recipe_instructions').style.border="1px solid #cc0000";
		error=error+"> You must provide instructions for your recipe\n";
	}	
	if(document.getElementById('recipe_name') && !document.getElementById('recipe_name').value){
		document.getElementById('recipe_name').style.border="1px solid #cc0000";
		error=error+"> You must provide your name\n";
	}
	if(document.getElementById('recipe_email') && !document.getElementById('recipe_email').value){
		error=error+"> You must provide a valid email address \n";
		document.getElementById('recipe_email').style.border="1px solid #cc0000";
	}


	if(error){
		alert (error);
		}else{
		if(document.getElementById('recipeform')){
			document.getElementById('recipeform').submit();
		}
	}
}





function boxsetinit(){
	if(!maxcount){
		var maxdiv = document.getElementById('boxsetmaxcount');
		maxcount = parseInt(maxdiv.className);
//		alert(maxcount);
	}
//	alert(maxcount);		
	initConn = new XHConn();
	initConn.connect("/boxset.php", "POST", "func=init&max="+maxcount, init_res);
}

function init_res(data){
	bottlearray = data.responseText;
	//alert(bottlearray);
	addImagesToBox();
}


function addToBoxSet(id,title,path,addcookie){
	if(addcookie === undefined){
		addcookie = 1;
	}
	if(!maxcount){
		var maxdiv = document.getElementById('boxsetmaxcount');
		maxcount = parseInt(maxdiv.className);
		//alert(maxcount);
	}
	var boxsetdiv = document.getElementById('pid'+id);
	var backup = boxsetdiv.innerHTML;
		if(count >= maxcount) {
			alert("your box set is full");
			var iHTML = backup;
		} else {
			if(backup.length < 5) {
				var iHTML = '<p><a href="'+path+'">'+title+'</a> x 1 (<a href="javascript:void(0);" onclick="javascript:removeFromBoxSet(\''+id+'\');">remove 1 item</a>)</p>';
				indivcount = 1;
				count++;
			} else {
				var indivcount = parseInt(backup.substr(backup.length-102,1));
				indivcount += 1;
				indivcount = indivcount+'';
				var iHTML = backup.substr(0,backup.length-102);
				//alert(iHTML);
				iHTML += indivcount + ' (<a href="javascript:void(0);" onclick="javascript:removeFromBoxSet(\''+id+'\');">remove 1 item</a>)</p>';
				count++;
			}
			// add to form
			var theForm = document.getElementById('addboxsetform');
			if(!document.getElementById('inpid'+id)){
				var inp = document.createElement('input');
				inp.setAttribute('type','hidden');
				inp.setAttribute('id','inpid'+id);
				inp.setAttribute('name','inpid'+id);
				inp.setAttribute('value',indivcount);
				theForm.appendChild(inp);
			} else {
				var tmp = document.getElementById('inpid'+id);
				tmp.value = indivcount;
			}
			countdown = maxcount - count;
			var countdownspan = document.getElementById('boxsetcountdownval');
			var countdowndiv = document.getElementById('boxsetcountdown');
			if(countdown == 0){
				countdowndiv.innerHTML = '<p>Your box set is now complete.</p>';
			} else {
				countdownspan.innerHTML = countdown;
			}
			// add to cookie
			if(addcookie>0){
//				var cookiecontents = readCookie('boxset_'+maxcount);
//				if(!document.cookie.match('boxset_'+maxcount)){
//					document.cookie = 'boxset_'+maxcount+'='+id+';expires=0;path=/;';
//				} else {
//					var cookiecontents = readCookie('boxset_'+maxcount);
//					document.cookie = 'boxset_'+maxcount+'='+cookiecontents+','+id+';expires=0;path=/;';
//				}
				// add to session
				var myConn = new XHConn();
				var bottleinfo="func=addBottleToSession&bottle="+id+"&max="+maxcount;
				myConn.connect("/boxset.php", "POST", bottleinfo, addBottles_res);
				//addImagesToBox();
			}

		}
		
	if(count == maxcount){
		showBuyButton(1);
		basketisfull = true;
	} else {
		showBuyButton(0);
	}

	boxsetdiv.innerHTML = iHTML;
	//alert(boxsetdiv.innerHTML);
	//alert(count);
}

function removeFromBoxSet(id){
	var boxsetdiv = document.getElementById('pid'+id);
	var backup = boxsetdiv.innerHTML;
	var indivcount = parseInt(backup.substr(backup.length-102,1));
	var theForm = document.getElementById('addboxsetform');
	if(indivcount < 2){
		iHTML = '';
		// remove hidden input
		var inp = document.getElementById('inpid'+id);
		theForm.removeChild(inp);
		indivcount = 0;
		//alert('empty');
	} else {
		indivcount -= 1;
		indivcount = indivcount+'';
		var iHTML = backup.substr(0,backup.length-102);
		//alert(iHTML);
		iHTML += indivcount + ' (<a href="javascript:void(0);" onclick="javascript:removeFromBoxSet(\''+id+'\');">remove 1 item</a>)</p>';
		var tmp = document.getElementById('inpid'+id);
		tmp.value = indivcount;
		
	}
	count--;
	countdown = maxcount - count;
	if(!basketisfull) {
		var countdownspan = document.getElementById('boxsetcountdownval');
		countdownspan.innerHTML = countdown;
	} else {
		countdowndiv = document.getElementById('boxsetcountdown');
		countdowndiv.innerHTML = '<p>Add <span id="boxsetcountdownval">'+countdown+'</span> bottle(s) to complete you boxset.</p>';
		basketisfull = false;
	}
	

//	var cookiecontents = readCookie('boxset_'+maxcount);
//	var cookiearray = cookiecontents.split(",");
//	var cookienewarray = new Array();
	var allowcount = parseInt(indivcount);
/*	alert(allowcount);
	for(i=0;i<cookiearray.length;i++){
		if((cookiearray[i] == id)){
			if(allowcount > 0){
				cookienewarray.push(cookiearray[i]);
			}
			allowcount--;
		} else {
			cookienewarray.push(cookiearray[i]);
		}
	}
	var cookiestring = '';
	for(x=0;x<cookienewarray.length;x++){
		cookiestring += cookienewarray[x]+',';
	}
	cookiestring = cookiestring.substr(0,cookiestring.length-1);
	document.cookie = 'boxset_'+maxcount+'='+cookiestring+';expires=0;path=/;';
*/
	
	var myConn = new XHConn();
	var bottleinfo="func=removeBottleFromSession&bottle="+id+"&max="+maxcount+"&indivcount="+indivcount;
	myConn.connect("/boxset.php", "POST", bottleinfo, removeBottles_res);
	
	
	
	showBuyButton(0);
	boxsetdiv.innerHTML = iHTML;
	//alert(count);
}

function addImagesToBox(){
	//remove images first
	if (bottlearray.length > 2) {
		for (i = 1; i < 5; i++) {
			var imgdiv = document.getElementById('bottle' + i);
			imgdiv.innerHTML = '';
		}
	}

	var images = bottlearray.split("|");
	//alert(images);
	for(i=0;i<images.length;i++){
		if(maxcount == 2){
			var imgcount = i+1;
		} else {
			var imgcount = i+1;
		}
		if(imgcount > 0){
			var imgdiv = document.getElementById('bottle'+imgcount);
			imgdiv.innerHTML = images[i];
		}
	}
}


function showBuyButton(dir){
	if(document.getElementById('boxsetbuybutton')){
		var button = document.getElementById('boxsetbuybutton');
		if(dir > 0){
			//alert('show buy button');
			button.style.display = "block";
		} else {
			//alert('hide buy button');
			button.style.display = "none";
		}
	}
}


function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function addBottles_res(data) {
	bottlearray=data.responseText;
	addImagesToBox();
	//alert(bottlearray);
}

function removeBottles_res(data){
	bottlearray=data.responseText;
	addImagesToBox();
	//alert(bottlearray);
}



//============================================================================================
/** XHConn - Simple XMLHTTP Interface - bfults@gmail.com - 2005-04-08        **
 ** Code licensed under Creative Commons Attribution-ShareAlike License      **
 ** http://creativecommons.org/licenses/by-sa/2.0/                           **/
if(document.getElementById('statusbar')){
	var oldStatusBackground=document.getElementById('statusbar').style.backgroundImage;
}
function XHConn()
{
  var xmlhttp, bComplete = false;
  try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
  catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
  catch (e) { try { xmlhttp = new XMLHttpRequest(); }
  catch (e) { xmlhttp = false; }}}
  if (!xmlhttp) return null;
  this.connect = function(sURL, sMethod, sVars, fnDone)
  {
    if (!xmlhttp) return false;
    bComplete = false;
    sMethod = sMethod.toUpperCase();

    try {
    	//before load, set statusbar to loading icon
    	if(document.getElementById('statusbar')){
    		document.getElementById('statusbar').style.backgroundImage="url(/duocms-resources/icons/loading2.gif)";
    	}
    		
      if (sMethod == "GET")
      {
        xmlhttp.open(sMethod, sURL+"?"+sVars, true);
        sVars = "";
      }
      else
      {
        xmlhttp.open(sMethod, sURL, true);
        xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
        xmlhttp.setRequestHeader("Content-Type",
          "application/x-www-form-urlencoded");
      }
      xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && !bComplete){
        	//after loaded set statusbar back to old background
        	if(document.getElementById('statusbar') && oldStatusBackground){
	    		document.getElementById('statusbar').style.backgroundImage=oldStatusBackground;
    		}else if(document.getElementById('statusbar')){
    			document.getElementById('statusbar').style.backgroundImage='';
    		}
        	
          bComplete = true;
          fnDone(xmlhttp);
        }};
      xmlhttp.send(sVars);
    }
    catch(z) { return false; }
    return true;
  };
  return this;
}

//JSON Parser = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 

(function () {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        s = {
            array: function (x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function (x) {
                return String(x);
            },
            'null': function (x) {
                return "null";
            },
            number: function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            object: function (x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        v = x[i];
                        f = s[typeof v];
                        if (f) {
                            v = f(v);
                            if (typeof v == 'string') {
                                if (b) {
                                    a[a.length] = ',';
                                }
                                a.push(s.string(i), ':', v);
                                b = true;
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            string: function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };

    Object.prototype.toJSONString = function () {
        return s.object(this);
    };

    Array.prototype.toJSONString = function () {
        return s.array(this);
    };
})();

String.prototype.parseJSON = function () {
    try {
        return (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(this)) &&
            eval('(' + this + ')');
    } catch (e) {
        return false;
    }
};


function whichBrs(){
	var agt = navigator.userAgent.toLowerCase();
	if (agt.indexOf("firefox") != -1) 
		return 'firefox';
	if (agt.indexOf("safari") != -1) 
		return 'safari';
	if (agt.indexOf("msie") != -1) 
		return 'ie';
	if (agt.indexOf('\/') != -1) {
		if (agt.substr(0, agt.indexOf('\/')) != 'mozilla') {
			return navigator.userAgent.substr(0, agt.indexOf('\/'));
		}
		else 
			return 'Netscape';
	}
	else 
		if (agt.indexOf(' ') != -1) 
			return navigator.userAgent.substr(0, agt.indexOf(' '));
		else 
			return navigator.userAgent;
}



