/**
 * Javascripts for 3hita.ru
 *
 * @author Victor Bolshov
 */

/**
 * make object `obj' change its CSS class to 'inputFocus'
 * @param DOMElement obj
 */
function inputFocusIn(obj) {
	obj.className = 'inputFocus';
}

/**
 * make object `obj' change its CSS class to 'inputBlur'
 * @param DOMElement obj
 */
function inputFocusOut(obj) {
	obj.className = 'inputBlur';
}

/**
 * clear input value in case it has not been already cleared with this function
 * @param DOMElement input
 */
function iclear(input) {
	if (!input.tagName || !(input.tagName == 'INPUT')) return false;
	with (input) {
		if (!getAttribute('icleared')) {
			setAttribute('icleared', 'true');
			value = '';
		}
	}
	return true;
}

/**
 * Clear 'href' attribute for hyperlinks that won't really change location
 */
function smart_hyperlinks() {
	try {
		links = document.links
		if (links.length) {
			var current_location      = window.location.href
			current_location          = current_location.toString()
			current_location_relative = current_location.replace(/^[a-z]+\/\/[^\/]+/, '')
			var i = 0
			var node, href, inner, span;
			while (node = links.item(i++)) {
				href = node.getAttribute('href')
				href = href.toString()
				if (!href || 
					(href == current_location) || 
					(href == current_location+"#") || 
					(href == current_location+"/#") || 
					(href == current_location_relative) || 
					(href == current_location_relative+"#") || 
					(href == current_location_relative+"/#") || 
					(href == "./") || 
					(href == "#") || 
					(href == "./#")) {
					node.removeAttribute('href')
				}
			}
		}
	} catch (e) {
		alert(e.message)
	}
}

/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

/**
 * Make an hash from a string
 * return hash
 */
function string2hash(str) {
	var output = {}, all_items, single_item, i
	if (str && str.trim()) {
		all_items = str.split("I")
		for (i = 0; i < all_items.length; ++i) {
    		single_item = all_items[i].split("-")
    		if (single_item.length == 2 && single_item[1] > 0) {
    			output[single_item[0]] = single_item[1]
    		}
    	}
	}
	return output
}

/**
 * Make a string from a hash
 * return string
 */
function hash2string(hash) {
	var output = [], i
	for (i in hash) {
		output[output.length] = i + "-" + hash[i]
	}
	return output.join("I")
}

/**
 * Get basket from cookie as hash
 * return hash
 */
function basketCookie2Array() {
	var b
	if (b = getCookie("h3[basket]")) {
    	return string2hash(b)
    }
    return {}
}

/**
 * get expiration date for a cookie
 */
function getCookieExpirationDate() {
	var dt = new Date()
	dt.setMonth(dt.getMonth() + 3)
	return dt
}

/**
 * Write Basket to Cookie
 * return void
 */
function writeBasketCookie(b_hash) {
	b = new Array()
    for (i in b_hash) {
    	b[b.length] = i+"-"+b_hash[i]
    }
    setCookie("h3[basket]", b.join("I"), getCookieExpirationDate(), "/")
}
/**
 * Delete Basket Cookie
 * return void
 */
function deleteBasketCookie() {
	deleteCookie("h3[basket]", "/")
}

/**
 * create the prototype on the String object
 * adding trim() method
 */
String.prototype.trim = function() {

 // skip leading and trailing whitespace
 // and return everything in between
  var x=this;
  x=x.replace(/^\s*(.*)/, "$1");
  x=x.replace(/(.*?)\s*$/, "$1");
  return x;
}

// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
	if(!radioObj) return ""
	var radioLength = radioObj.length;
	if(radioLength == undefined)
	if(radioObj.checked) return radioObj.value
	else return ""
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
	if(!radioObj) return
	var radioLength = radioObj.length
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString())
		return
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true
		}
	}
}

/**
 * convert string to integer
 */
function myParseInt(value, min, max, default_value) {
	min = arguments.length > 1 ? myParseInt(min) : false
	max = arguments.length > 2 ? myParseInt(max) : false
	default_value = arguments.length > 3 ? myParseInt(default_value) : false
	var i = parseInt(value)
	
	if (isNaN(i) || 
		(min !== false && i < min) || 
		(max !== false && i > max)) {
		return (default_value === false) ? value : default_value;
	}
	return i
}

function toggleDiv(id){
	obj = document.getElementById(id);
	tmp = obj.style.display;
	if (tmp == 'none') obj.style.display='block';
	else obj.style.display='none';
}
