
/* ####### Misc functions #######  */

function getObj(name) 
{
	obj = document.getElementById(name);
	return obj;
}

function getTags(name)
{
	obj = document.getElementsByTagName(name);
	return obj;
}

function newTag(name)
{
  obj = document.createElement(name);
  return obj;
}


/* ####### Functions run POST window load, see applyDOMAlterations ########  */

function addMenuDropShadown()
{
  var menuWrapper = getObj('menu_wrapper');
  if (menuWrapper != null)
  {
    var dropShad = newTag('div');
    dropShad.id = "menu_bottom_drop_shadow";
    var dropShadImg = newTag('img');
    dropShadImg.setAttribute("src", "/images/app/menu_corner.gif");
    dropShadImg.id = "menu_bottom_drop_shadow_image";
    menuWrapper.appendChild(dropShad);
    menuWrapper.appendChild(dropShadImg);
  }
}

function initWebsiteEnabler()
{
  var radioYes = getObj("site_active_yes");
  var radioNo = getObj("site_active_no");
  if (radioYes != null)
  {
    radioYes.onclick = function()
    {
      showHideWebsite("yes");
    }
    if (radioYes.checked == true)
    {
     showHideWebsite("yes");    
    }    
  }
  if (radioNo != null)
  {
    radioNo.onclick = function()
    {
      showHideWebsite("no");
    }
  }
}

function showHideWebsite(value)
{
  var wrapper = getObj("website_input_details");
  if (value == "yes")
  {
    wrapper.style.display = "block";
  } else if (value == "no")
  {
    wrapper.style.display = "none";
  }
}


function applyTooltips(){
    var body_element = document.getElementsByTagName("body")[0];
    var toolTipWrapper = document.createElement('div');
    toolTipWrapper.setAttribute('id', 'tool_tip_wrapper');
    body_element.appendChild(toolTipWrapper);
    var elements = document.getElementsByTagName("span");
    for (var i = 0; i < elements.length; i++) {
        if (elements[i].getAttribute("class") == "apply_tooltip" || elements[i].className == "apply_tooltip") {
            var nbspace = document.createTextNode(' ');
            elements[i].appendChild(nbspace);
            var toolTipIcon = document.createElement('img');
            toolTipIcon.setAttribute('src', '/images/app/tt_icon.gif');
            toolTipIcon.setAttribute('class', 'tooltip_icon');
            toolTipIcon.setAttribute('border', '0');
            toolTipIcon.onmouseover = function(){
                toolTip(this);
                return false;
            }
            if (!toolTipIcon.getAttribute('onmouseover')) {
                toolTipIcon.setAttribute("onmouseover", "toolTip(this)");
            }
            toolTipIcon.onmouseout = function(){
                var wrapper = document.getElementById('tool_tip_wrapper');
                var element = document.getElementById('toolTip');
                wrapper.removeChild(element);
                return false;
            }
            elements[i].appendChild(toolTipIcon);
        }
    }
}

function toolTip(obj){
    var eleID = obj.parentNode.id;
    var find_pos = findPos(obj);
    var windowWidth = document.body.clientWidth;
    var windowHeight = document.body.clientHeight;
    var offset_left = find_pos[0];
    var offset_top = find_pos[1];
    if (eleID != null) {
        var eleInformation = getInformation(eleID);
        var theDescription = document.createElement('p');
        var theHeading = document.createElement('strong');
        var theBR = document.createElement('br');
        var theBR2 = document.createElement('br');
        theDescription.setAttribute('title', document.createTextNode(eleInformation[1]));
        var textArr = eleInformation[2].split("##br##");
        var textDescription = document.createElement("span");
        for (var x = 0; x < textArr.length; x++) {
            textDescription.appendChild(document.createTextNode(textArr[x]));
            textDescription.appendChild(document.createElement("br"));
        }
        var textHeading = document.createTextNode(eleInformation[1]);
        theHeading.appendChild(textHeading);
        theHeading.appendChild(theBR);
        theHeading.appendChild(theBR2);
        theDescription.appendChild(theHeading);
        theDescription.appendChild(textDescription);
        var toolTipDiv = document.createElement('div');
        toolTipDiv.setAttribute('id', 'toolTip');
        document.getElementById('tool_tip_wrapper').appendChild(toolTipDiv);
        document.getElementById('toolTip').appendChild(theDescription);
        if (offset_left + 350 > windowWidth) {
            offset_left = offset_left - 350;
        }
        var ttHeight = document.getElementById('toolTip').clientHeight;
        if (offset_top + ttHeight > windowHeight) {
            offset_top = offset_top - ttHeight - 25;
        }
        offset_left = offset_left + 5;
        offset_top = offset_top + 20;
        document.getElementById('toolTip').style.left = offset_left + 'px';
        document.getElementById('toolTip').style.top = offset_top + 'px';
    }
}

function findPos(obj){
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft, curtop];
}


function getInformation(eleTitle){
    var info = new Array();
    info.push(new Array("tt_supplier_profile_logo","Company Logo","This logo will appear on your company profile.##br##Please note that this will be resized to fit on our websites design"));
    // products
    info.push(new Array("tt_product_title","Product Title","This title will be used to describe the product on our network of sites.##br####br##Please type this carefully as it will be used for indexing by our search engine."));
    info.push(new Array("tt_product_price","Item Price","This should be the cost of your product.##br####br##Providing this information is key to promoting your product and will greatly increase your chance of a sale or customer enquiry.##br####br##This is also used by our search engine so we can provide customers a product list by price."));
    info.push(new Array("tt_product_brief_description","Brief Description","This should be a short and sharp paragraph covering the main details of the product.##br####br##This text will be used to hook the customer into clicking on the product to get more detailed information"));
    info.push(new Array("tt_product_main_image","Main Image","This image should detail the entire product.Formats allowed are gif, jpg, bmp and png.##br####br##It will be used to help grab customers attention so should be as detailed as possible.##br####br##Please note you also have the option to upload extra images (below), these will be displayed when the user clicks to view more detail about your product."));
    info.push(new Array("tt_product_link","Product Link","This is an optional field, If you want customers to be able to click directly to your product listing on your site then please populate this. ##br####br##If this is left blank then the customer will be directed to your website (detailed in your profile).##br####br##If that isn't populated then the product will not be clickable"));
    info.push(new Array("tt_product_full_description","Full Details","When a customer clicks on a product to get additional information the contents of the Full Details box will be displayed. This is ideal to detail product specifications."));
    info.push(new Array("tt_product_detail_images","Detail Images","These images should cover certain details of your product. Formats allowed are gif, jpg, bmp and png.##br####br##Ideally these images should include close-up shots of detailed areas of your product.")); 
    info.push(new Array("tt_product_tags","Product Tags","Please click any of the tags below to associate with your product. You may click more than one."));     
    
    info.push(new Array("tt_sample", "This is a sample tool-tip", "These tool-tips provide helpful hints and information"));
    for (var i = 0; i < info.length; i++) {
        if (info[i][0] == eleTitle) {
            var retArray = new Array(info[i][0], info[i][1], info[i][2]);
            return retArray;
        }
    }
    var notFoundArray = new Array("tt_not_found", "Tooltip Unavailable", "Unfortunately this tool tip cannot be displayed. Please contact the application developer if you see this notification")
    if (!retArray) {
        return notFoundArray;
    }
}

function findPos(obj)
{
  var curleft=curtop=0;
  if(obj.offsetParent)
  {
    curleft=obj.offsetLeft;
    curtop=obj.offsetTop;
    while(obj=obj.offsetParent)
    {
      curleft+=obj.offsetLeft;
      curtop+=obj.offsetTop;
    }
  }
  return[curleft,curtop];
}


// used to pre-check / uncheck all the categorys in a defined industry
function checkIndustryChildren(obj)
{
  var industry_id = obj.id.split("ind_")[1];
  for (var x = 0; x <=100; x++)
  {
    var cBox = getObj('cat_checkbox_'+industry_id+x)
    if (cBox != "undefined")
    {
      cBox.checked = obj.checked;
    }
  }
}

function openExternalWindow(object){
    window.open(object.href, '', 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
}


function initSiteSelectionTool() 
{
  var selectTool = getObj('site_selection_tool');
  if (selectTool != null)
  {
    selectTool.onchange = function()
    {
      getObj('edit-product-sites').submit();
      return false;
    }
  }
}

function initProductListSelector()
{
  var selectType = getObj('report_type_selector');
  if (selectType != null)
  {
    selectType.onchange = function()
    {
      var product_sel_wrapper = getObj('product_dropdown_wrapper');
      if (product_sel_wrapper != null)
      {
        if (selectType.value == "product_link")
        {
          product_sel_wrapper.style.display = 'block';
        } else
        {
          product_sel_wrapper.style.display = 'none';
        }
      }
      return false;
    }
  }
}

// to minimise the number of characters in a text-area //
function showChar(obj, max_allowed)
{
	len = obj.value.length;
	var cur = (max_allowed * 1) - len;
	if (cur < 0) 
	{
		var obj2 = getObj("product_description_field");
		var str = obj2.value.substring(0, (max_allowed * 1));
		obj2.value = str;
	} else
	{
		var obj2 = getObj("chars_remaining");
		var str = document.createTextNode(cur);
		obj2.replaceChild(str,obj2.firstChild);
	}
}



function applyProductDescriptionEvent()
{
	var textareaEle = getObj('product_description_field');
	if (textareaEle != null)
	{
		textareaEle.onkeyup = function()
		{
			showChar(this, 200);
		}
		textareaEle.onBlur = function()
		{
			showChar(this, 200);
		}	
	}
}

/* ####### DOM alterations, performed after window load ####### */

function applyDOMAlterations() 
{
	var hrefItems = window.location.href.split("/");
	menuItem = hrefItems[4];
	sectionItem = hrefItems[5];
  
  submitImg = getObj("img_submit");
  if (submitImg != null) 
  {
    if (menuItem == "" || menuItem == null || (sectionItem == "logon") || (sectionItem == "logoff"))
    {
      // we're at the login page
      submitImg.src = "/images/app/btn_login.gif";
    } else
    {
      submitImg.src = "/images/app/btn_submit.gif";    
    }
  }
  if (getObj("under_login") != null) {
      var currDate = new Date();
      var currYear = currDate.getFullYear();
      HTML = "<br /><br /><div class=\"fw_text\" style=\"text-align: center\">Copyright &copy;" + currYear + " Metropolis International Group Ltd. All rights reserved</span>";
      getObj("under_login").innerHTML = HTML;
  }  
  
  
  if (sectionItem == "edit-category" || sectionItem == "add-category")
  {
    initWebsiteEnabler();
  }
  if (sectionItem == "edit-product-sites" || sectionItem == "categories" || menuItem == "banners-and-buttons" || sectionItem == "supplier-profile" || sectionItem == "add-profile")
  {
    initSiteSelectionTool();
  }
  if (sectionItem == "clicks")
  {
    initProductListSelector();
  }
  if (sectionItem == "add-product" || sectionItem == "edit-product")
  {
  	applyProductDescriptionEvent();
  }
  addMenuDropShadown();
  applyTooltips();
}

window.onload = applyDOMAlterations;	

