/**
 * The utilities.js file provides additional functions, many built on top of yahoo
 * @module starwood utilities
 * @requires yahoo-dom-event
 */


// can be used in place of window.onload or yuiEvent.addListener(window,"load",...).
// In theory, this fires when the closing body tag is drawn (before window.onload).

/**
 * @deprecated
 * @param String url
 * @param String param
 * @param String val
 * @return String
 */
SW.tools.setUrlParameter = function(url,param,val){
    return SW.tools.Url.setParameter(url,param,val);
}
SW.tools.Url = {
    /**
     * used to add or change value of parameter in url
     * var url = SW.tools.setUrlParamter(document.location.href,"propID",mySelect.value);
     * @param url
     * @param param
     * @param val
     * @return String
     */
    setParameter:function(url,param,val){
        var curPairs;
        var paramPair;
        var hashString = "";
        if(url.indexOf("#") > -1){
            hashString = url.substr(url.indexOf("#")+1);
            url = url.substring(0,url.indexOf("#"));
        }
        var allPairs = [];
        var urlParts = url.split('?');

        if(urlParts.length>1){
            curPairs = urlParts[1].split('&');
            curPairs.forEach(function(paramPair){
                var paramParts = paramPair.split('=');
                if(paramParts[0] != param){
                    allPairs.push(paramParts[0] + '=' + (typeof paramParts[1] != "undefined" ? paramParts[1]:'') );
                }
            });
        }
        if(val !== null && typeof val !== 'undefined'){ 
            allPairs.push(param + '=' + val);
        }
        return urlParts[0] + '?' + allPairs.join('&') + (hashString ? "#"+hashString:"");

    },
    getParameter:function(url,param){
        var i,urlParts,curPairs,paramParts;
        if(url.indexOf("#") > -1){
            url = url.substring(0,url.indexOf("#"));
        }
        urlParts = url.split('?');
        if(urlParts.length>1){
            curPairs = urlParts[1].split('&');
            for(i = 0; i < curPairs.length; i++){
                paramPair = curPairs[i];
                paramParts = paramPair.split('=');
                if(paramParts[0] === param){
                    return paramParts[1];
                }
            }
        }
        return null;
    },
    getHash:function(url){
        if(url.indexOf("#") > -1){
           return url.substring(url.indexOf("#")+1);
        }
        return "";
    }
};
/**
 * add to img tags which are using [semi]transparent png's to fix IE6 issue
 * This is only way to avoid *ALL* IE6 issues! (including browser freezing/locking up)
 * sample:
 *      <img src="/path/to/myImage.png" width="233" height="82" onload="SW.tools.iePNGLoader(this);" />
 * @param img
 */
SW.tools.iePNGLoader = function(img){
    if (navigator.userAgent.indexOf("MSIE") > -1 && parseInt(navigator.appVersion) <= 6) {
      var pSrc = img.src;
      img.onload = null;
      img.src = "/common/images/shim.gif";
      img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, src='" + pSrc + "')";
    }
}                                                                   

// Begin Code from YUI: Colorpicker
var HCHARS="0123456789ABCDEF";
/**
 * Converts decimal rgb values into a hex string
 * 255,255,255 -> FFFFFF
 * @method rgb2hex
 * @param r {int|[int, int, int]} the red value, or an
 *        array containing all three parameters
 * @param g {int} the green value
 * @param b {int} the blue value
 * @return {string} the hex string
 */
SW.tools.rgb2hex =  function(r, g, b) {
	var f=this.dec2hex;
	return f(r) + f(g) + f(b);
};

/**
 * Converts an int 0...255 to hex pair 00...FF
 * @method dec2hex
 * @param n {int} the number to convert
 * @return {string} the hex equivalent
 */
SW.tools.dec2hex = function(n) {
	n = parseInt(n, 10);
	n = (n > 255 || n < 0) ? 0 : n;

	return HCHARS.charAt((n - n % 16) / 16) + HCHARS.charAt(n % 16);
};
// End code from YUI: Colorpicker



// used in conjunction with secure json calls
// new yuiConnect( secureJsonUrl("/path/to/myData.jsp?someID=45") );
SW.tools.secureJsonUrl = function(url){
  return SW.tools.Url.setParameter(url,"_jsk",SW.Cookie.get("JSESSIONID"));
}

/*
### set cookie ###
  --> set basic session cookie
    SW.tools.Cookie.set("sid","somevalue");

  --> set permanent cookie
    SW.tools.Cookie.set("sid","somevalue","NEVER");

  --> set cookie to expire sometime in the future
    var exDate = new Date();
    expires.setMonth(expires.getMonth()+1);
    SW.tools.Cookie.set("sid","somevalue",expires);

### get cookie ###
  --> get value of cookie
    SW.tools.Cookie.get("sid");
    
### remove cookie ###
  --> remove cookie
    SW.tools.Cookie.remove("sid");
*/
SW.tools.Cookie = {
  values:[],
  loaded:false,
  set:function(name, value, expires, path, domain, secure){
    var cookieValue = new Array();
    cookieValue.push(name + "=" + escape(value));
    if(typeof expires != "undefined"){
      if(typeof expires == "string"){
        if(expires.toUpperCase() == "NEVER"){
          expires = new Date();
          expires.setFullYear(expires.getFullYear()+10);
        }else if(expires.toUpperCase() == "REMOVE"){
          expires = new Date();
          expires.setFullYear(expires.getFullYear()-1);
        }
      }
      cookieValue.push("expires=" + expires.toGMTString());
    }
    if(typeof path == "undefined"){
      path = "/";
    }
    cookieValue.push("path="+ path);
    if(typeof domain != "undefined"){
      cookieValue.push("domain=" + domain);
    }
    if(secure){
      cookieValue.push("secure");
    }
    document.cookie = cookieValue.join("; ");
    SW.tools.Cookie.loaded = false;
  },
  get:function(name){
    if (!SW.tools.Cookie.loaded) {
      SW.tools.Cookie._readCookie();
    };
    for (var i=0; i<SW.tools.Cookie.values.length; i++) {
      if (SW.tools.Cookie.values[i].name == name) {
        return SW.tools.Cookie.values[i].value;
      };
    }
    return "";
  },
  remove:function(name){
    SW.tools.Cookie.set(name,"","REMOVE");
  },
  // internal method
  _readCookie:function(){
    var cookieString = document.cookie;
    var paramPairs = cookieString.split("; ");
    var i,splitPair;
    SW.tools.Cookie.values = [];
    for (i=0; i<paramPairs.length; i++) {
      splitPair = paramPairs[i].split("=");
      if (splitPair.length == 2) {
        SW.tools.Cookie.values.push({
          name:unescape(splitPair[0]),
          value:unescape(splitPair[1])
        });
      }
    };
    SW.tools.Cookie.loaded = true;
  }
};

SW.tools.getSkinName = function(){
     return document.location.pathname.split("/")[1];
 };

SW.tools.Xml = {
    /**
     *
     * @param node - reference to parent node
     * @param tagname - tagname for which you want to get it's "innerText"
     * @return String
     */
    getSubNodeText:function(node, tagname){
        var returnValue;
        subNode = node.getElementsByTagName(tagname);
        if (subNode[0] != null) {
            returnValue = subNode[0].textContent || subNode[0].text;
            if(typeof returnValue == 'undefined' && subNode[0].firstChild){
                returnValue = subNode[0].firstChild.nodeValue;
            }
        }
        if(!returnValue){
            returnValue = "";
        }
        return returnValue;
    }
};

// helper methods to scrub html for data (taken from results.js - consider making common version)

SW.tools.Html = (function(){
    var yuiDom = YAHOO.util.Dom,
        yuiLang = YAHOO.lang;
    
    function dataToType(data, type, defaultVal) {
        var val = defaultVal;
        switch (type) {
            case "string":
                val = (data === "") ? defaultVal:data;
                break;
            case "array":
                if(data === ""){
                   val = defaultVal;
                }else{
                    val = data.split(",");
                }
                break;
            case "boolean":
                val = (data === "true") ? true:defaultVal;
                break;
            case "float":
                val = parseFloat(data);
                if (isNaN(val)) {
                    val = defaultVal;
                }
                break;
            case "int":
                val = parseInt(data, 10);
                if (isNaN(val)) {
                    val = defaultVal;
                }
                break;
            default:
                break;
        }
        return val;
    }
    var self = {
        getDataFromInput:function(root, className, type, defaultVal) {
            var input = yuiDom.getElementsByClassName(className, "input", root);
            var val = defaultVal;
            if (input && input[0]) {
                val = dataToType(input[0].value, type, defaultVal);
            }
            return val;
        },
        getDataFromTag:function(root, tagName, className, type, defaultVal) {
            var result = yuiDom.getElementsByClassName(className, tagName, root);
            var val = defaultVal;
            if (result && result[0]) {
                val = dataToType(yuiLang.trim(result[0].innerHTML), type, defaultVal);
            }
            return val;
        },
        getClearDiv:function(){
            var div = document.createElement("div");
            yuiDom.addClass(div,"clearDiv");
            return div;
        },
        appendClearDiv:function(parentNode){
            parentNode.appendChild(self.getClearDiv());
        }
    };
    return self;
})();