// ==========================================================================
// Shared Functions

// ==========================================================================
// Adds events to be executed after the document is loaded.
// By Simon Willison (See http://simonwillison.net)
// ==========================================================================

function addLoadEvent(func) {
  var oldonload = window.onload
  if (typeof window.onload != 'function') {
    window.onload = func
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload()
      }
      func()
    }
  }
}


// ==========================================================================
// Returns the check radio button for a form for with a class name
// ==========================================================================

function checkedRadioButton(radioClass) {
  $$(radioClass).each(function(radio) {
    if (radio.checked==true)
      checked = radio
  })
  return checked 
}

// ==========================================================================
// Clears the search box content when it gets focus.
// ==========================================================================

function clearInputBox(box) {
  box.setAttribute("value", "")
}

// ==========================================================================
// Removes border-top of 1st LI element in the sidebar menu.
// ==========================================================================

function removeSideMenuBorder() {
  listElements = $$('#sidebar div.side-menu li')
  listElements[0].style.borderTop = "none"
}

// ==========================================================================
// Adjust height of products in ul.product-list to highest
// ==========================================================================

function adjustProductItemHeight() {
  productImages = $$('#content ul.product-list li img')
  imageContainers = $$('#content ul.product-list li p.product-photo')
  productItems = $$('#content ul.product-list li')
  totalItems = productItems.length
  
  highestImage = 0
  highestItem = 0
  
  // Checking for highest image
  for(i = 0; i < totalItems; i++) {
    image = productImages[i]
    
    imageHeight = image.getHeight()
    if (imageHeight > highestImage) highestImage = imageHeight
  }
  
  // Applying highest image value to all items
  for(i = 0; i < totalItems; i++) {
    imageContainer = imageContainers[i]
    
    imageContainer.style.height = highestImage + "px"
  }  
  
  // Checking for highest item
  for(i = 0; i < totalItems; i++) {
    activeItem = productItems[i]
    
    itemHeight = activeItem.getHeight()
    if (itemHeight > highestItem) highestItem = itemHeight
  }
  
  // Applying highest item value to all items
  for(i = 0; i < totalItems; i++) {
    activeItem = productItems[i]
    
    activeItem.style.height = highestItem + "px"
  }
}

// ==========================================================================
// Vertically centers mini-thumbnails on product page
// ==========================================================================

function adjustMiniThumbnails() {
  var images = $$('#content div.show-product div.images ul li img')
  
  images.each(function(image) {
    var offset = image.clientHeight / 2
    
    image.setStyle({
      marginTop: '-' + offset + 'px'
    })
  })
}

// ==========================================================================
// Centers and resizes images vertically in their boxes.
// Mosty applicable to: Product thumbnails, Features, Certificates.
// ==========================================================================

function adjustImagesByImageSet() { 
  // Creates an array of possible images to align. Each image set needs
  // different height values that are not available in the DOM.
  var imageSets = Array("thumbnails","certificates-features","product-images","mini-thumbnails")
  
  // Loops through all the images depending on the set.
  imageSets.each(function(set) {
    if (set == imageSets[0]) adjustProductThumbnails('#content ul.product-list img')
    
    if (set == imageSets[1]) adjustPropertiesImages()
    
    if (set == imageSets[2]) adjustProductThumbnails('#content div.product-images div.list p.image img')
    
    if (set == imageSets[3]) adjustMiniThumbnails()
  })
}

function adjustProductThumbnails(set) {
  // Searches for items and adjusts them to their container height
  var images = $$(set)
  if (images.length == 0) return false
  var parentHeight = 114
  var maxWidth = 110
  var maxHeight = 110
  imgResize(images,maxWidth,maxHeight)
  imgVerticalCentering(images,parentHeight)
}

function adjustPropertiesImages() {
  var images = $$('#content div.certificate img','#content div.feature img')
  if (images.length == 0) return false
  var parentHeight = 39
  var maxWidth = 43
  var maxHeight = 35
  imgResize(images,maxWidth,maxHeight)
    imgVerticalCentering(images,parentHeight)
  var settingProperties = $$('#content div.settings-list img')
  if (settingProperties.length == 0) {
    return false
  } else {
    imgResize(images,maxWidth,maxHeight)
  }
}

function imgVerticalCentering(images,parentHeight) {
  images.each(function(image) {
    var imgHeight = image.clientHeight
    var margin = (parentHeight-imgHeight)/2 + "px"
    image.setStyle({marginTop: margin})
  })
}

function imgResize(images,maxWidth,maxHeight) {
  images.each(function(image) {
    var size_x = image.clientWidth
    var size_y = image.clientHeight
    if (size_x > maxWidth) {
      var coeff = maxWidth/size_x
      var final_x = maxWidth + "px"
      var final_y = Math.round(size_y*coeff) + "px"
      image.setStyle({
        width: final_x,
        height: final_y
      })
    }
    if (size_y > maxHeight) {
      var coeff = maxHeight/size_y
      var final_x = Math.round(size_x*coeff) + "px"
      var final_y = maxHeight + "px"
      image.setStyle({
        width: final_x,
        height: final_y
      })
    }
  })
}

function loadAdjustImages() {
  document.body.onload += adjustImagesByImageSet();
}


// ==========================================================================
// Controls item activation / deactivation
// ==========================================================================

function setUnassigned() {
  var items = document.getElementsByClassName("not_assigned")
  if (items.length == 0) {
    return false
  }
  items.each(function(item) {
    item.style.opacity = 0.15
  })
}

function loadUnassigned() {
  document.body.onload += setUnassigned();
}


// ==========================================================================
// Cookie functions
// ==========================================================================

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;
}

function eraseCookie(name) {
  createCookie(name,"",-1);
}


// ==========================================================================
// Print Rep Co-ordinates
// ==========================================================================

function doesRepExist() {
  var repInfo = readCookie('rep_info');
  return repInfo != undefined && !repInfo.blank();
}

function repData() {
  return unescape(readCookie('rep_info')).replace(/\+/g, ' ').evalJSON();
}

function printRepInfo() {
    if (doesRepExist()) {
      var output = new EJS({url: '/javascripts/views/representatives/header.ejs'}).render(repData());
      document.write(output);
    }
}

function printContactInfo() {  
  if (doesRepExist()) {
    var output = new EJS({url: '/javascripts/views/representatives/contact.ejs'}).render(repData());
    document.write(output);
  } else {
    var output = new EJS({url: '/javascripts/views/representatives/contact_default.ejs'}).render({});
    document.write(output);  
  }
}

function printContactLink() {  
  if (doesRepExist()) {
    var output = new EJS({url: '/javascripts/views/representatives/contact_link.ejs'}).render(repData());
    document.write(output);
  } else {
    var output = new EJS({url: '/javascripts/views/representatives/contact_link_default.ejs'}).render({});
    document.write(output);  
  }
}

function printContactSupport() {  
  if (doesRepExist()) {
    var output = new EJS({url: '/javascripts/views/representatives/support.ejs'}).render(repData());
    document.write(output);
  } else {
    var output = new EJS({url: '/javascripts/views/representatives/support_default.ejs'}).render({});
    document.write(output);  
  }
}

function printContactPhoto() {
    if (doesRepExist()) {
      var output = new EJS({url: '/javascripts/views/representatives/photo.ejs'}).render(repData());
      document.write(output);
    }
}