
jQuery.noConflict();



//onload start init
window.onload = init;

//ie6 select box width hack


//initAllSelects
var flippedMat = 0;
var fourColorMat = new Array();
var fourColorMatPlusWhite = new Array();
var fourColorMatAndPlus = new Array();
var sizes = new Array();
var images = new Array();
var materials = new Array();
var allColors = new Array();
var flippedCoating = 0;
var fourColorCoating = new Array();
var coatings = new Array();
var quantities = new Array();
var colors = new Array();
var selectedItems = new Array();
var qOther = "";
//qs
var qsParm = new Array();
var json;
var defaultWarningText = "We recommend that you do not use designs on your letterhead or envelopes that contain large areas of dark or intense colors as the uncoated paper stock that we use tends to soak these colors into the paper giving undesired results.";

function init(){
	roundAllCorners();

	initIE6Selects();
	
	//prepare select boxes for label requestor
	initAllSelects();
	
	//parse the query string
	qs();
	
	//get all business product dropdowns in json form
	getAllBusinessInfo();
	
	if( selectedItems["product"] !=null){
		setWarning(); setMaterials();setSizes();setQuantities();setColors();setImage();
		if(jQuery("#quantitiesRadio").attr("checked") == true)
			enableOther();
	}
	
	
    ms_miniZoom();
	
}
function getAllBusinessInfo(){
					var self = this;				
        new Ajax.Request('/php/getBusinessQuantities.php',
          {method:'get',
			asynchronous:false,
            onSuccess: function(payload){
                json = payload.responseText.evalJSON();
 				self.initBusSup(json);
          },
            onFailure: function(){ 
            alert('Failed to get Page Items...')
          }
          });

}
function initBusSup(json){
               selectedItems["product"] = json.selected["product"];
                selectedItems["material"] = json.selected["material"];
                selectedItems["quantity"] = json.selected["quantity"];
                selectedItems["size"] = json.selected["size"];
                selectedItems["color"] = json.selected["color"];
                qOther = json.selected["quantityOther"] ? json.selected["quantityOther"]:"";
                for(var i=0;i<json.sizes.length;i++){
               			var sizeIsSelected = "";
               			if(selectedItems["size"] == json.sizes[i].id)
               			sizeIsSelected = " selected = 'selected' ";
               			
						sizes[i] = 
						jQuery("<option class='"+
						((json.sizes[i].product).toLowerCase()).replace(/\s+/g,'')+
						"'  value='"+
						json.sizes[i].id+
						"'"+
						sizeIsSelected+
						"> "+
						json.sizes[i].size+
						"</option>");				

               }
               for(var i=0;i<json.colors.length;i++){
               		var colorIsSelected = "";
               			if(selectedItems["color"] == json.colors[i].id){
               			colorIsSelected = " selected = 'selected' ";
               			}
						colors[i] = 
						jQuery("<option class='"+
						((json.colors[i].product).toLowerCase()).replace(/\s+/g,'')+
						"' value='"+
						json.colors[i].id+
						"' "+
						colorIsSelected+
						" > "+
						json.colors[i].color+
						"</option>\n");				

               }               
               for(var i=0;i<json.materials.length;i++){
               			var matIsSelected = "";
               			if(selectedItems["material"] == json.materials[i].id)
               			matIsSelected = " selected = 'selected' ";
               			
						materials[i] = 
						jQuery("<option class='"+
						((json.materials[i].product).toLowerCase()).replace(/\s+/g,'')+
						"' value='"+
						json.materials[i].id+
						"'"+
						matIsSelected+
						"> "+
						json.materials[i].material+
						"</option>\n");				

               }   

               for(var i=0;i<json.image.length;i++){
               			
						images[i] = json.image[i].image;				

               } 
                         
               for(var i=0;i<json.quantities.length;i++){
               		var qIsSelected = "";
               			if(selectedItems["quantity"]){
							for(var j=0; j< selectedItems["quantity"].length; j++){
								if(selectedItems["quantity"][j] == json.quantities[i].id){
									qIsSelected = " checked = 'checked' ";
								}
							}
               			}
               			
               		
               		
               		if(json.quantities[i].quantity=="Quote Higher Quantities"){
						quantities[i] = 
						jQuery("<li><input id='quantitiesRadio' name='businessQuantities[]' class='"+
						((json.quantities[i].product).toLowerCase()).replace(/\s+/g,'')+
						"' type='checkbox' onclick='enableOther()' value='"+
						json.quantities[i].id+
						"' "+
						qIsSelected+
						" > "+
						json.quantities[i].quantity+
						"</input></li>\n");				
					}
					else{
						quantities[i] = 
						jQuery("<li><input  name='businessQuantities[]' class='"+
						((json.quantities[i].product).toLowerCase()).replace(/\s+/g,'')+
						"' type='checkbox' value='"+
						json.quantities[i].id+
						"' "+
						qIsSelected+
						" > "+
						json.quantities[i].quantity+
						"</input></li>\n");					
					}
					
               }   
}
function setSizes(){
	
	//clear everything out because we will replace it
	clearSizes(true);
	
	//get the string of the product selected
	var productSelected = $("productsDD")[$("productsDD").selectedIndex].innerHTML;	
	
	//if the product isnt the first selection (i.e. blank string)...
	if(productSelected !=""){
		//our sizes have a class name that is equal to the product name minus spaces and to lower case
		var productToClass = (productSelected.toLowerCase()).replace(/\s+/g,'');
		
		//if product isnt the blank option insert those sizes
		if(productToClass!=""){
			for(var i=0; i < sizes.length; i++){
				if(jQuery(sizes[i]).attr("class") == productToClass)
					jQuery("#sizesDD").append(sizes[i]);
			}
		}
		//if their was no sizes inserted then default to 1 option
		if($("sizesDD")[0] != null){
			//$("sizesDD")[0].selected = true;
		}
		else{
			$("sizesDD").insert("<option value='none'>Coming Soon...</option>");
		}
	}
	//if it is the blank string then just give one selection for the sizes...
	else{
		$("sizesDD").insert("<option value='none'>Please Select a Product</option>");
	}
	 
}

function setMaterials(){
	
	//clear everything out because we will replace it
	clearMaterials(true);
	
	//get the string of the product selected
	var productSelected = $("productsDD")[$("productsDD").selectedIndex].innerHTML;	
	
	//if the product isnt the first selection (i.e. blank string)...
	if(productSelected !=""){
		//our materials have a class name that is equal to the product name minus spaces and to lower case
		var productToClass = (productSelected.toLowerCase()).replace(/\s+/g,'');
		
		//if product isnt the blank option insert those materials
		if(productToClass!=""){
			for(var i=0; i < materials.length; i++){
				if(jQuery(materials[i]).attr("class") == productToClass)
					jQuery("#materialsDD").append(materials[i]);
			}
		}
		//if their was no materials inserted then default to 1 option
		if($("materialsDD")[0] != null){
			//$("materialsDD")[selectedItems["material"]].selected = true;
		}
		else{
			$("materialsDD").insert("<option value='none'>Coming Soon...</option>");
		}
	}
	//if it is the blank string then just give one selection for the materials...
	else{
		$("materialsDD").insert("<option value='none'>Please Select a Product</option>");
	}
	 
}

function setQuantities(){
	var foundQ = false;

	//clear everything out because we will replace it
	clearQuantities();

	//get the string of the product selected
	var productSelected = $("productsDD")[$("productsDD").selectedIndex].innerHTML;	
	
	//if the product isnt the first selection (i.e. blank string)...
	if(productSelected !=""){
		//our materials have a class name that is equal to the product name minus spaces and to lower case
		var productToClass = (productSelected.toLowerCase()).replace(/\s+/g,'');
		
		//if product isnt the blank option insert those materials
		if(productToClass!=""){
			for(var i=0; i < quantities.length; i++){
				if(jQuery(quantities[i]).find("input").attr("class") == productToClass){
					jQuery("#radioButtons").append(quantities[i]);
				}
			}
		}
		if(jQuery("#radioButtons").find("input")[0] != null){
			jQuery("#radioButtons input").each(function(){		
					if(selectedItems["quantity"]){			
						for(var j=0; j< selectedItems["quantity"].length; j++){
							if(selectedItems["quantity"][j] == jQuery(this).val()){
								foundQ= true;
							}
						}
					}
			});
				if(!foundQ){
					jQuery("#radioButtons").find("input")[0].checked=true;
					qOther = "";
					jQuery("#quantitiesRadioOther").val("");
				}
		}

	}
	//if it is the blank string then just give one selection for the materials...
	else{
		$("radioButtons").insert("Please Select a Product...");
		jQuery("#quantitiesRadioOther").val("");
		qOther = "";
	}
	 
}

function setColors(){
	
	//clear everything out because we will replace it
	clearColors(true);
	
	//get the string of the product selected
	var productSelected = $("productsDD")[$("productsDD").selectedIndex].innerHTML;	
	
	//if the product isnt the first selection (i.e. blank string)...
	if(productSelected !=""){
		//our colors have a class name that is equal to the product name minus spaces and to lower case
		var productToClass = (productSelected.toLowerCase()).replace(/\s+/g,'');
		
		//if product isnt the blank option insert those colors
		if(productToClass!=""){
			for(var i=0; i < colors.length; i++){
				if(jQuery(colors[i]).attr("class") == productToClass)
					jQuery("#colorsDD").append(colors[i]);
			}
		}
		//if their was no colors inserted then default to 1 option
		if($("colorsDD")[0] != null){
			//$("colorsDD")[0].selected = true;
		}
		else{
			$("colorsDD").insert("<option value='none'>Coming Soon...</option>");
		}
	}
	//if it is the blank string then just give one selection for the colors...
	else{
		$("colorsDD").insert("<option value='none'>Please Select a Product</option>");
}
}
	 

function clearSizes(noDummy){
	jQuery("#sizesDD").empty();
	if(!noDummy)
		jQuery("#sizesDD").append("<option value='none'>Please Select a Product</option>");
}

function clearMaterials(noDummy){
	jQuery("#materialsDD").empty();
	if(!noDummy)
		jQuery("#materialsDD").append("<option value='none'>Please Select a Product</option>");
		
}
function clearQuantities(noDummy){

	jQuery("#radioButtons").empty();


}
function clearColors(noDummy){
	jQuery("#colorsDD").empty();
	if(!noDummy)
		jQuery("#colorsDD").append("<option value='none'>Please Select a Product</option>");

}
function setWarning(){
	var product = $("productsDD")[$("productsDD").selectedIndex];
	if(product.className=="warning"){
		$("warningText").innerHTML= defaultWarningText;
		$("warningText").show();
	}
	else{
		$("warningText").hide();
	}
	$("othersBox").hide();
}
function setImage(){
	var productSelected = $("productsDD").value;
	if(productSelected == "none")
		document.getElementById('businessImg').src = "/img/sliderImages/slider10a.png";
	else
		document.getElementById('businessImg').src = "/img/businessScroll/"+images[productSelected-1];
}
function initIE6Selects(){
	new YAHOO.Hack.FixIESelectWidth("productsDD");
	new YAHOO.Hack.FixIESelectWidth("sizesDD");
	new YAHOO.Hack.FixIESelectWidth("materialsDD");
	new YAHOO.Hack.FixIESelectWidth("colorsDD");
}


function initAllSelects(){
	sizes = $("sizesDD").childElements();
	materials = $("materialsDD").childElements();
	colors = $("colorsDD").childElements();
}

function qs() {
	qsParm['color'] = null;
	var query = window.location.search.substring(1);
	var parms = query.split('&');
	for (var i=0; i<parms.length; i++) {
		var pos = parms[i].indexOf('=');
			if (pos > 0) {
			var key = parms[i].substring(0,pos);
			var val = parms[i].substring(pos+1);
			qsParm[key] = val;
			}
	}
//alert(qsParm['color']);
}

function roundAllCorners(){
      /*ROUND THE TOP OF THE FORM*/
      var settings1 = {
          tl: { radius: 10 },
          tr: { radius: 10 },
          bl: { radius: 0 },
          br: { radius: 0 },
          antiAlias: true,
          autoPad: false,
          validTags: ["div"]
      };

      var myBoxObject1 = new curvyCorners(settings1, "tempClass");
      myBoxObject1.applyCornersToAll();
      
      /*ROUND THE BOTTOM OF THE FORM*/
      var settings2 = {
          tl: { radius: 4 },
          tr: { radius: 4 },
          bl: { radius: 10 },
          br: { radius: 10 },
          antiAlias: true,
          autoPad: true,
          validTags: ["form"]
      };

      var myBoxObject2 = new curvyCorners(settings2, "formRegister");
      myBoxObject2.applyCornersToAll();
      
	/*ROUND THE CALCULATOR */
      var settings3 = {
          tl: { radius: 10 },
          tr: { radius: 10 },
          bl: { radius: 10 },
          br: { radius: 10 },
          antiAlias: true,
          autoPad: false,
          validTags: ["div"]
      };

      var myBoxObject3 = new curvyCorners(settings3, "labelCalc");
      myBoxObject3.applyCornersToAll();
}
function enableOther(){

if(qOther)
jQuery("#quantitiesRadioOther").val(qOther);
else{
jQuery("#quantitiesRadioOther").val("");
}
if(jQuery("#quantitiesRadio").attr("checked"))
	$("othersBox").show();
else
	$("othersBox").hide();
}
function disableOther(){
jQuery("#quantitiesRadioOther").val("");

qOther = "";
$("othersBox").hide();
}


var ms_totalImages = 0;
var ms_imgType =[];
var ms_imgInfo =[];
var ms_imgPath =[];
var ms_imgWidth =[];
var ms_imgHeight =[];
var ms_currentImage = 0;
var self = this;
var isIE = jQuery.browser.msie;
	
jQuery(document).ready(function(){

	document.onkeydown = function(e){
	  if (e == null) { // ie
		keycode = event.keyCode;
	  } else { // mozilla
		keycode = e.which;
	  }
	  if(keycode == 27){ // escape, close box
		closeTip();
	  } 
	}
         
});




function ms_miniZoom(){	
	
	
	jQuery(".businessImg").click(function(e){
		
		var imgSrc = jQuery(this).attr("src");
		var imgName = jQuery("#productsDD option:selected").html()
		imgName = imgName=="" ? "Business Supplies" : imgName;
		var imgNum = jQuery("#productsDD option:selected").val();
		var imgDesc = ""
		imgNum == "none" ? (imgDesc = "") : imgDesc = json.image[imgNum-1].description;
		
		var pageHeight = getPageSize()[1];										  
		var self = this;

		//set the height of the overlay
		if(!isIE)
			jQuery("div.overlayDark").css("height",pageHeight).fadeIn(300,function(){ 
			
			//Create the markup								  
			jQuery("body").append("<div class='miniZoomTip' id='miniZoomTip'  ><div id='miniZoomTipClose' ><a href='javascript:void(0)'>x close</a></div>"+
			"<img width=\"342\" height=\"300\" class='noie6trans' src='"
			+imgSrc+"'/><div id='miniZoomTitle'>"
			+imgName+"</div><div id='miniZoomDescr'>"
			+imgDesc+"</div>"
			+"</div>");

							
			var imgWidth = jQuery("#miniZoomTip").find("img").width();
			jQuery("#miniZoomTip").css("width",imgWidth);				
			putCenter("miniZoomTip");
 
			
			//close button
			jQuery("#miniZoomTipClose").bind("click",function(e){
				
				closeTip();
				return false;
			});
			
			return false;
			
			});
		else{
			jQuery("div.overlayDark").css("height",pageHeight).show();
			
			//Create the markup								  
			jQuery("body").append("<div class='miniZoomTip' id='miniZoomTip'  ><div id='miniZoomTipClose' ><a href='javascript:void(0)'>x close</a></div>"+
			"<img width=\"342\" height=\"300\" class='noie6trans' src='"
			+imgSrc+"'/><div id='miniZoomTitle'>"
			+imgName+"</div><div id='miniZoomDescr'>"
			+imgDesc+"</div>"
			+"</div>");

			//Hide all select boxes or else the popup will go behind ie6;
			if(isIE)
				jQuery("div.form-row select").hide();
							
			var imgWidth = jQuery("#miniZoomTip").find("img").width();
			jQuery("#miniZoomTip").css("width",imgWidth);				
			putCenter("miniZoomTip");
 
			
			//close button
			jQuery("#miniZoomTipClose").bind("click",function(e){
				
				closeTip();
				return false;
			});
			
			return false;
			
			}

			
			
		});

							

    	
};

function closeTip(){
				jQuery("div.overlayDark").hide();
				
				if(isIE)
					jQuery("div.form-row select").show();
				
				jQuery("#miniZoomTip").remove();
}


//taken from here http://codesnippets.joyent.com/user/winton/tag/javascript
function putCenter(item)  {
  item = $(item);
  var xy = item.getDimensions();
  var win = windowDimensions();
  var scrol = scrollOffset();
  item.style.left = (win[0] / 2) + scrol[0] - (xy.width / 2) + "px";
  item.style.top = (win[1] / 2) + scrol[1] - (xy.height / 2) + "px";
}

function fullScreen(item) {
  item = $(item);
  var win = windowDimensions();
  var scrol = scrollOffset();
  item.style.height = scrol[1] + win[1] + "px";
}
function windowDimensions() {
  var x, y;
  if (self.innerHeight) {
    // all except Explorer
    x = self.innerWidth;
    y = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) {
    // Explorer 6 Strict Mode
    x = document.documentElement.clientWidth;
    y = document.documentElement.clientHeight;
  } else if (document.body) {
    // other Explorers
    x = document.body.clientWidth;
    y = document.body.clientHeight;
  }
  if (!x) x = 0;
  if (!y) y = 0;
  arrayWindowSize = new Array(x,y);
  return arrayWindowSize;
}
function scrollOffset() {
  var x, y;
  if (self.pageYOffset) {
    // all except Explorer
    x = self.pageXOffset;
    y = self.pageYOffset;
  } else if (document.documentElement && document.documentElement.scrollTop) {
    // Explorer 6 Strict
    x = document.documentElement.scrollLeft;
    y = document.documentElement.scrollTop;
  } else if (document.body) {
    // all other Explorers
    x = document.body.scrollLeft;
    y = document.body.scrollTop;
  }
  if (!x) x = 0;
  if (!y) y = 0;
  arrayScrollOffset = new Array(x,y);
  return arrayScrollOffset;
}
////END put center



//taken from lightbox.js
function getPageSize(){
	        
	     var xScroll, yScroll;
		
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		
		var windowWidth, windowHeight;
		
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
	
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}

		return [pageWidth,pageHeight];
	}


