var alwaysOpen = false

var numCats = 14
var indentSpeed = 4
var stagger = 13
var s = new Array()
for (i=0; i<numCats; i++) {s[i] = (numCats-1-i)*stagger}
var maxIndent = stagger*16.5
var indent = -maxIndent

var heightSpeed = 6
var maxHeight = 313
var minHeight = 20
var height = minHeight

var sideSteps = 5
var maxWidth, minWidth
if (usingIE()) {
   maxWidth = 78
   minWidth = 57
}
else {
   maxWidth = 70
   minWidth = 52
}
var maxMargin = 5
var minMargin = 0
var margin = minMargin
var width = minWidth

var openmenu
var closemenu

function setMargins() {
   for (i=0; i<numCats; i++) {
      var newIndent = indent + s[i]
      if (newIndent > 0) newIndent = 0
      document.getElementById(ids[i]).style.marginRight = newIndent
   }
}

function adjustTrigger() {
   document.getElementById("menu").style.width = width
   //document.getElementById("menu").style.marginLeft = (maxWidth - width) / 2 + 10
   //document.getElementById("menu").style.marginRight = (maxWidth - width) / 2
   document.getElementById("trigger").style.margin = margin
}

function openMenu() {
   document.getElementById("trigger").style.color = "white"
   document.getElementById("menu").style.borderColor = "white"
   clearTimeout(closemenu)
   if (width < maxWidth) {
      width += (maxWidth - minWidth) / sideSteps
      if (width > maxWidth) width = maxWidth
      margin += (maxMargin - minMargin) / sideSteps
      if (margin > maxMargin) margin = maxMargin
      adjustTrigger()
   }
   else if (height < maxHeight) {
      if (height == minHeight) document.getElementById("menu").style.borderRightStyle = "solid"
      height += heightSpeed
      if (height > maxHeight) height = maxHeight
      document.getElementById("menu").style.height = height
   }
   indent += indentSpeed
   setMargins()
   if (indent < 0) openmenu = setTimeout("openMenu()",15)
}

function closeMenu() {
   clearTimeout(openmenu)
   for (i=0; i<numCats; i++) {
      document.getElementById(ids[i]).style.color = faded[i]
   }
   if (!alwaysOpen) {
       if (indent > -maxIndent) {
          indent -= indentSpeed*1.5
          setMargins()
       }
       else if (height > minHeight) {
          height -= heightSpeed*1.5
          if (height < minHeight) height = minHeight
          document.getElementById("menu").style.height = height
          if (height == minHeight) document.getElementById("menu").style.borderRightStyle = "none"
       }
       else {
          width -= (maxWidth - minWidth) / sideSteps
          if (width < minWidth) width = minWidth
          margin -= (maxMargin - minMargin) / sideSteps
          if (margin < minMargin) margin = minMargin
          adjustTrigger()
       }
       if (width > minWidth) closemenu = setTimeout("closeMenu()",15)
       else {
          document.getElementById("trigger").style.color = "#7f7f7f"
          document.getElementById("menu").style.borderColor = "#7f7f7f"
       }
    }
}

function menuCategory(cat) {
   id = "c" + cat.substr(0,3)
   var x
   for (i=0; i<numCats; i++) {
      if (ids[i].search(id) == 0) x = i
   }
   document.getElementById(id).style.color = colours[x]
   openMenu()
   if (cat=="Products") return statusProducts()
   else if (cat=="About us") return statusAboutUs()
   else if (cat=="Home") return statusHome()
   else return statusCategory(cat)
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function findStyleRule(styleName) {
  if (usingIE()) {
     for (i = 0; i < document.styleSheets.length; i++) {
       for (j = 0; j < document.styleSheets[i].rules.length; j++) {
         if (document.styleSheets[i].rules[j].selectorText.toLowerCase() == styleName.toLowerCase()) {
           return document.styleSheets[i].rules[j];
         }
       }
     }
  }
  else {
     for (i = 0; i < document.styleSheets.length; i++) {
       for (j = 0; j < document.styleSheets[i].cssRules.length; j++) {
         if (document.styleSheets[i].cssRules[j].selectorText == styleName) {
           return document.styleSheets[i].cssRules[j];
         }
       }
     }
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var cookieLifespan = 0

var minSizes = new Array()
minSizes[0] = [18,20]
minSizes[1] = [4,5]
minSizes[2] = [6,7,8,9]

var orderFontSpeed = 0.15
var orderWidthSpeed = 15
var orderPaddingSpeed = 0.25
var orderTitleSpeed = 0.25
var orderTitlesSpeed = 0.35
var orderTitleSpacingSpeed = 0.195
var orderIconSpeed = 0.0016

var fontSize = 11
var padding = 0
var titleSize = 13
var titlesSize = 0
var minIconWidth = 18
var minIconHeight = 20
var titleLetterSpacing = -10
var orderText = findStyleRule("td.orderText").style
var cells = findStyleRule("td.orderDetails").style
var titles = findStyleRule("td.name").style
var iconSpeeds = new Array()
var minOrderWidth = 174
var maxOrderWidth = 1029
var numAnimSteps = (maxOrderWidth - minOrderWidth) / orderWidthSpeed

function warnFireFoxUsers() {
   alert("After adding this bookmark, you may wish to uncheck the box labelled \"Load this bookmark in the sidebar\", found by right-clicking and selecting 'Properties' on the file in the 'Bookmarks' menu.")
}
function addFavourite() {
    try {
        var title = frames['superDaddy'].document.title
        var link = frames['superDaddy'].location.href
        if (link.indexOf("home.htm") > 0) {title = "Colour Of Water"; link = "http://www.colourofwater.com/"}
        if (window.sidebar) {warnFireFoxUsers(); window.sidebar.addPanel(title, link, "")}
        else if (window.external && window.ActiveXObject) window.external.AddFavorite(link, title)
        else alert("Sorry, your browser doesn't support this feature")
    }
    catch(e) {
        if (window.sidebar) {warnFireFoxUsers(); window.sidebar.addPanel("Colour Of Water", "http://www.colourofwater.com/", "")}
        else if (window.external && window.ActiveXObject) window.external.AddFavorite('http://www.colourofwater.com/', "Colour Of Water")
        else alert("Sorry, your browser doesn't support this feature")
    }
}
function mouseOn(what) {
   what.style.color = "#dddddd"
}
function mouseOff(what) {
   what.style.color = "#7f7f7f"
}

var anythingAdded = false
function addToOrder(title, type, price, icon, colour) {
   if (usingWebKit()) {
      alert("Sorry, your browser doesn't support our order system.\nPlease use an alternative web browser or email us with your order.")
      return
   }

   if (incrementOrder(title, type)) return

   var row = document.createElement("tr")
   row.title = title
   row.style.color = colour

   var thumb = document.createElement("td")
   thumb.align = "center"
   thumb.innerHTML = "<img src='"+icon+"' width='18' height='20' onclick='popup(event)'\>"
   thumb.className = "orderDetails"

   var quantity = document.createElement("td")
   quantity.align = "center"
   quantity.innerHTML = "<a class='quantifier' href='#' onclick='changeQuantity(event, -1)'>-</a><div style='display:inline'>1&times</div><a class='quantifier' href='#' onclick='changeQuantity(event, 1)'>+</a>"
   quantity.title = ""
   quantity.className = "orderDetails"

   var name = document.createElement("td")
   name.innerText = title
   name.className = "orderDetails name"

   var item = document.createElement("td")
   item.innerHTML = type
   item.title = "£" + price.toFixed(2) + " each"
   item.className = "orderDetails"

   var cost = document.createElement("td")
   cost.innerHTML = "£" + price.toFixed(2)
   cost.align = "right"
   cost.className = "orderDetails"

   row.appendChild(thumb)
   row.appendChild(quantity)
   row.appendChild(name)
   row.appendChild(item)
   row.appendChild(cost)
   document.getElementById("items").appendChild(row)

   updateOrderAnimation(0)
   updateTotal(price)
}

var rowMem = 0
function removeFromOrder() {
   document.getElementById("items").removeChild(rowMem)
   rowMem = 0
}

function changeQuantity(clicked, addSub) {
   var div = usingIE()? clicked.srcElement.parentElement.getElementsByTagName("div").item(0) : clicked.target.parentNode.getElementsByTagName("div").item(0)
   var currentQuantity = parseInt(div.innerHTML)
   if (currentQuantity > 0) {
      var thisItem = usingIE()? clicked.srcElement.parentElement.parentElement.getElementsByTagName("td") : clicked.target.parentNode.parentNode.getElementsByTagName("td")
      updateQuantity(thisItem, addSub)
      if (currentQuantity+addSub == 0) {
         rowMem = usingIE()? clicked.srcElement.parentElement.parentElement : clicked.target.parentNode.parentNode
         setTimeout("removeFromOrder()", 300)
      }
   }
}

function updateQuantity(row, addSub) {
   var currentQuantity = parseInt(row.item(1).getElementsByTagName("div").item(0).innerHTML)
   if (currentQuantity > 0) {
      var singlePrice = parseFloat(row.item(4).innerHTML.substr(1)) / currentQuantity
      row.item(1).getElementsByTagName("div").item(0).innerHTML = (currentQuantity+addSub) + "&times"
      row.item(4).innerHTML = "£" + (singlePrice * (currentQuantity+addSub)).toFixed(2)
      updateTotal(singlePrice * addSub)
   }
}

function incrementOrder(title, type) {
   var items = document.getElementById("items").getElementsByTagName("tr")
   for (i=0; i<items.length; i++) {
      if (items.item(i).getAttribute("title") == title) {
         var thisItem = items.item(i).getElementsByTagName("td")
         if (thisItem.item(3).innerHTML == type) {
            updateQuantity(thisItem, 1)
            return true
         }
      }
   }
   return false
}

var total = 0
function updateTotal(diff) {
   total += diff
   document.getElementById("total").innerHTML = "£" + (total+0.0001).toFixed(2)
   saveOrder()
   if (!anythingAdded && !readCookie("numItems")) alert("Your browser appears to be blocking cookies from our website.\nPlease be aware that this will result in your order being cleared if you refresh or navigate away from us before checking out.\nThis includes not being able to ammend your order after proceeding to Google Checkout.\nPlease allow your browser to accept our cookies if you wish to avoid these inconveniences.")
   anythingAdded = true
}

var noSaving = false
function saveOrder() {
   if (noSaving) return
   var items = document.getElementById("items").getElementsByTagName("tr")
   var numItems = 0
   for (i=0; i<items.length; i++) {
      var row = items.item(i).getElementsByTagName("td")
      var currentQuantity = parseInt(row.item(1).getElementsByTagName("div").item(0).innerHTML)
      if (currentQuantity > 0) {
         createCookie("title"+numItems, items.item(i).title, cookieLifespan)
         createCookie("type"+numItems, row.item(3).innerHTML, cookieLifespan)
         createCookie("quantity"+numItems, currentQuantity, cookieLifespan)
         createCookie("price"+numItems, parseFloat(row.item(4).innerHTML.substr(1)) / currentQuantity, cookieLifespan)
         createCookie("icon"+numItems, row.item(0).getElementsByTagName("img").item(0).src, cookieLifespan)
         createCookie("colour"+numItems, items.item(i).style.color, cookieLifespan)
         numItems++
      }
   }
   createCookie("numItems", numItems, cookieLifespan)
}

function popup(clicked) {
   var picture = new Image()
   picture.src = usingIE()? clicked.srcElement.getAttribute("src") : clicked.target.getAttribute("src")
   var preview = window.open("", "", "width="+(picture.width+(usingIE()? 30 : 0))+", height="+(picture.height+(usingIE()? 30 : 0)))
   preview.document.write("<html>")
   preview.document.write("<head>")
   preview.document.write("<title>"+(usingIE()? clicked.srcElement.parentElement.parentElement.getAttribute('title') : clicked.target.parentNode.parentNode.getAttribute('title'))+"</title>")
   preview.document.write("<style type=\"text/css\">")
   preview.document.write("body {background-color:black; background-image:url("+picture.src+"); background-repeat:no-repeat;")
   if (usingIE()) preview.document.write(" background-position:center;}")
   else preview.document.write("}")
   preview.document.write("</style>")
   preview.document.write("</head>")
   preview.document.write("<body></body>")
   preview.document.write("</html>")
}

var blankButton
var submission = false
function checkOrder() {
   if (submission) return false
   if (document.getElementById("items").getElementsByTagName("tr").length == 0) {
      if (!anythingAdded) alert("You have not yet added anything to your order; you can add items by using the 'Buy' buttons on the pop-up window for every image")
      else alert("You have removed everything from your order; please add more items to proceed")
      return false
   }
   if (rowMem) {
      alert("Please wait for the item to be removed from your order before you check out")
      return false
   }
   var text = ""
   for (i=0; i<document.getElementById("items").getElementsByTagName("tr").length; i++) {
      var row = document.getElementById("items").getElementsByTagName("tr").item(i)
      var cells = row.getElementsByTagName("td")
      if (cells.item(3).innerHTML == "Digital image") {
         var quantity = parseInt(cells.item(1).getElementsByTagName("div").item(0).innerHTML)
         if (quantity > 1) text += "You are about to order "+quantity+" copies of the original \""+row.title+"\" photograph\nYou will only receive one download, but will have permission to copy the digital image for "+(quantity-1)+" other "+(quantity > 2? 'people' : 'person')+"\n\n"
      }
   }
   if (text.length > 0 && !confirm(text + "If you are sure, click 'OK' to continue, otherwise click 'Cancel' to amend your order")) return false
   if (!readCookie("numItems") && !confirm("You are about to submit your order and enter Google Checkout, after which you will no longer be able to make any amendments\nClick 'OK' to proceed or 'Cancel' to remain on this page")) return false

   // Generate the checkout button
   document.getElementById("googlebutton").innerHTML = blankButton
   for (i=0; i<document.getElementById("items").getElementsByTagName("tr").length; i++) {
      var row = document.getElementById("items").getElementsByTagName("tr").item(i)
      var cells = row.getElementsByTagName("td")
      var entry = i+1

      var title = document.createElement("input")
      title.type = "hidden"
      title.name = "item_name_"+entry
      title.value = row.title

      var description = document.createElement("input")
      description.type = "hidden"
      description.name = "item_description_"+entry
      description.value = cells.item(3).innerHTML

      var quantity = document.createElement("input")
      quantity.type = "hidden"
      quantity.name = "item_quantity_"+entry
      var currentQuantity = parseInt(cells.item(1).getElementsByTagName("div").item(0).innerHTML)
      quantity.value = ""+currentQuantity

      var price = document.createElement("input")
      price.type = "hidden"
      price.name = "item_price_"+entry
      price.value = ""+(parseFloat(cells.item(4).innerHTML.substr(1)) / currentQuantity)

      var currency = document.createElement("input")
      currency.type = "hidden"
      currency.name = "item_currency_"+entry
      currency.value = "GBP"

      document.getElementById("googlebutton").appendChild(title)
      document.getElementById("googlebutton").appendChild(description)
      document.getElementById("googlebutton").appendChild(quantity)
      document.getElementById("googlebutton").appendChild(price)
      document.getElementById("googlebutton").appendChild(currency)

      if (description.value == "Digital image") {
         var digital = document.createElement("input")
         digital.type = "hidden"
         digital.name = "shopping-cart.items.item-"+entry+".digital-content.email-delivery"
         digital.value = "true"
         document.getElementById("googlebutton").appendChild(digital)
      }
   }
   submission = true
   return true
}

function reviewLogic() {
   if (document.getElementById("proceed").innerText == "Back to previous page") {
      history.back()
      return false
   }
   return true
}

var animation
function expandOrder() {
   clearInterval(animation)
   animation = setInterval("animateOrder()", 15)
   document.getElementById("inlineframe").style.visibility = "hidden"
   document.getElementById("options").style.visibility = "hidden"
   document.getElementById("proceed").innerText = "Back to previous page"
   document.getElementById("proceed").textContent = "Back to previous page"
   document.getElementById("proceed").style.width = "167px"
   titles.display = "inline"
}

function collapseOrder() {
   clearInterval(animation)
   animation = setInterval("unanimateOrder()", 15)
   document.getElementById("proceed").innerText = "Review..."
   document.getElementById("proceed").textContent = "Review..."
   document.getElementById("proceed").style.width = "0%"
   document.getElementById("items").style.letterSpacing = "0px"
   document.getElementById("checkout").style.display = "none"
}

var stepNumber = 0
function animateOrder() {
   if (stepNumber == numAnimSteps) {
      clearInterval(animation)
      document.getElementById("items").style.letterSpacing = "1px"
      document.getElementById("checkout").style.display = "inline"
   }
   else updateOrderAnimation(1)
}

function unanimateOrder() {
   if (stepNumber == 0) {
      clearInterval(animation)
      document.getElementById("inlineframe").style.visibility = "visible"
      document.getElementById("options").style.visibility = "visible"
      titles.display = "none"
   }
   else updateOrderAnimation(-1)
}

function updateOrderAnimation(step) {
      stepNumber += step
      document.getElementById("inlineframe").width = ""+(parseInt(document.getElementById("inlineframe").width) - orderWidthSpeed*step)
      document.getElementById("lefty").width = ""+(parseInt(document.getElementById("lefty").width) + orderWidthSpeed*step)
      fontSize += orderFontSpeed*step
      padding += orderPaddingSpeed*step
      titleSize += orderTitleSpeed*step
      titlesSize += orderTitlesSpeed*step
      titleLetterSpacing += orderTitleSpacingSpeed*step
      document.getElementById("items").style.fontSize = ""+fontSize
      cells.paddingLeft = ""+padding
      cells.paddingRight = ""+padding
      orderText.fontSize = ""+titleSize
      titles.fontSize = ""+titlesSize
      titles.letterSpacing = ""+titleLetterSpacing
      var icons = document.getElementsByTagName("img")
      var iconFactorMax = stepNumber * orderIconSpeed
      var iconFactorMin = 1 - stepNumber / numAnimSteps
      for (i=0; i<icons.length; i++) {
         var picture = new Image()
         picture.src = icons[i].src
         icons[i].width = ""+(minIconWidth * iconFactorMin + picture.width * iconFactorMax)
         icons[i].height = ""+(minIconHeight * iconFactorMin + picture.height * iconFactorMax)
      }
}

function createCookie(name,value,days) {
   if (days) {
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      var expires = "; expires="+date.toGMTString();
   }
   else var expires = "";
   document.cookie = name+"="+value+expires+"; path=/";
}

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;
}
