document.onmousemove = follow_mouse;

function in_array(needle, haystack) {
	var len = haystack.length;
	for (var x = 0; x <= len; x++) {
		if (haystack[x] == needle) { return true; } 
	}
	return false;
}

function check_all(lookup) {
	var inputs = dojo.query(lookup);
	inputs.forEach(
		function(input) {
			input.checked = true;
		}
	);
}

function dragStart(event, id) {
  var el;
  var x, y;

  // If an element id was given, find it. Otherwise use the element being clicked on.
  if (id) { dragObj.elNode = document.getElementById(id); }
  else {
    if (browser.isIE) { dragObj.elNode = window.event.srcElement; }
    else { dragObj.elNode = event.target; } 
		// If this is a text node, use its parent element.
    if (dragObj.elNode.nodeType == 3) { dragObj.elNode = dragObj.elNode.parentNode; }
  }

	// Get cursor position with respect to the page.
  if (browser.isIE || browser.isOpera) {
    x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
  }
  else  {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

	// Save starting positions of cursor and element.
  dragObj.cursorStartX = x;
  dragObj.cursorStartY = y;
  dragObj.elStartLeft  = parseInt(dragObj.elNode.style.left, 10);
  dragObj.elStartTop   = parseInt(dragObj.elNode.style.top,  10);
  if (isNaN(dragObj.elStartLeft)) { dragObj.elStartLeft = 0; }
  if (isNaN(dragObj.elStartTop))  { dragObj.elStartTop  = 0; }

  // Update element's z-index.
	dragObj.elNode.style.zIndex = ++dragObj.zIndex;

	// Capture mousemove and mouseup events on the page.
  if (browser.isIE) {
    document.attachEvent("onmousemove", dragGo);
    document.attachEvent("onmouseup",   dragStop);
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  else {
    document.addEventListener("mousemove", dragGo,   true);
    document.addEventListener("mouseup",   dragStop, true);
    event.preventDefault();
  }
}

function dragGo(event) {
  var x, y;

	// Get cursor position with respect to the page.
  if (browser.isIE || browser.isOpera) {
    x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
  }
  else {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

  // Move drag element by the same amount the cursor has moved.
  dragObj.elNode.style.left = (dragObj.elStartLeft + x - dragObj.cursorStartX) + "px";
  dragObj.elNode.style.top  = (dragObj.elStartTop  + y - dragObj.cursorStartY) + "px";
  if (browser.isIE) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  else { event.preventDefault(); }
}

function dragStop(event) {
	// Stop capturing mousemove and mouseup events.
  if (browser.isIE) {
    document.detachEvent("onmousemove", dragGo);
    document.detachEvent("onmouseup",   dragStop);
  }
  else {
    document.removeEventListener("mousemove", dragGo,   true);
    document.removeEventListener("mouseup",   dragStop, true);
  }
}

function follow_mouse(evt){
	pop_x = parseInt(mouseX(evt), 10);
	pop_y = parseInt(mouseY(evt), 10);
}

function mouseX(evt) {
	if (!evt) { evt = window.event; }
	if (evt.pageX) { return evt.pageX; }
	else if (evt.clientX) {
	   return ( evt.clientX + (document.documentElement.scrollLeft ) ? document.documentElement.scrollLeft : document.body.scrollLeft);
	} else {
		return null;
	}
}

function mouseY(evt) {
	if (!evt)  { evt = window.event; }
	if (evt.pageY) { return evt.pageY; }
	else if (evt.clientY) {
		   return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
	}
	else {
		return null;
	}
}

function get_window_dim(){
	var dim_arr = {};
	if( isIE ){
		dim_arr.window_w = document.body.clientWidth;
		dim_arr.window_h = document.body.clientHeight;
		dim_arr.scroll_l = document.body.scrollLeft;
		dim_arr.scroll_t = document.body.scrollTop;
	}else{
		dim_arr.window_w = innerWidth;
		dim_arr.window_h = innerHeight;
		dim_arr.scroll_l = pageXOffset;
		dim_arr.scroll_t = pageYOffset;
	}
	return dim_arr;
}

function format_currency(num) {
	return langNumberFormat(num);
}

function number_format(number, decimals, dec_point, thousands_sep) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://crestidg.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // *     example 1: number_format(1234.5678, 2, '.', '');
    // *     returns 1: 1234.57     
 
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point === undefined ? "." : dec_point;
    var t = thousands_sep === undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

function isArray(obj) {
	if (obj.constructor.toString().indexOf("Array") == -1) { 
		return false;
	}
	else {
		return true;
	}
}

function toggle_wait_main() {
	var content = dojo.byId('content_area');
	var indicator = dojo.byId('main_div_wait');
	// Min. height for loading indicator so that it isn't cut off, otherwise revert to default (which should match CSS definition).
	var new_height = (content.offsetHeight > 200)? content.offsetHeight : 1050;
	var new_status = (indicator.style.display == 'block')? 'none' : 'block';
	indicator.style.height = new_height + 'px';
	indicator.style.display = new_status;
}

// Dojo doesn't automatically convert arrays/objects into a form that can be retrieved by PHP, so this prepares the data first.
// Pass in an array/object of the key-value pairs to be prepared for xhr communication (can have nested arrays/objects).
// The second two parameters are for interal recursion only--do not pass anything into them.
function preparePostData(data, arr_key, ref_data) {
	// Copy the reference to the original object prior to recursion, since data will be a new subset at each calil.
	if (ref_data === undefined) {
		ref_data = data;
	}

	for (var i in data) {
		// If one of object's members is an object, recurse on that.
		if (typeof(data[i]) == 'object') {
			// Create a new key that will be used in the recursion to flatten the array/object's members.
			// During recursion we need to build onto the existing key.
			var new_key = (arr_key === undefined)? i : arr_key + '[' + i + ']';
			preparePostData(data[i], new_key, ref_data);
		}
		else {
			// Receiving values from the recursion.
			if (arr_key !== undefined) {
				// Put them into the original array using the reference so that we end up with all values flattened into lowest level.
				ref_data[arr_key + '[' + i + ']'] = data[i];
				// Remove the non-flattened data from the current level.
				delete(data[i]);
			}
		}
	}
}

function json_request(script, args, callback_func) {
	preparePostData(args);
	var request = {
		url: script,
		content: args,
		handleAs: 'json',
		handle: function(response) {
			toggle_wait_main();
			// Check for an error from Dojo
			if (response.name !== undefined && response.name == 'SyntaxError') {
				alert(NCMallClientTrans.getTranslation(222));
				return;
			}
			// If optional callback defined, execute it
			switch (typeof(callback_func)) {
				case 'string':
					eval(callback_func + '(response)');
					break;
				case 'function':
					callback_func(response);
					break;
			}
			// make the google urchin call here
			if(typeof urchinTracker == 'function') {				
				var _uacct = "UA-1152868-1";
				urchinTracker(script);
			}

		}
	};

	toggle_wait_main();
	dojo.xhrPost(request);
}

function json_request_get(script, args, callback_func) {
	preparePostData(args);
	var request = {
		url: script,
		content: args,
		handleAs: 'json',
		handle: function(response) {
			toggle_wait_main();
			// Check for an error from Dojo
			if (response['name'] != undefined && response['name'] == 'SyntaxError') {
				alert(NCMallClientTrans.getTranslation(222));
				return;
			}
			// If optional callback defined, execute it
			switch (typeof(callback_func)) {
				case 'string':
					eval(callback_func + '(response)');
					break;
				case 'function':
					callback_func(response);
					break;
			}
			// make the google urchin call here
			if(typeof urchinTracker == 'function') {				
				var _uacct = "UA-1152868-1";
				urchinTracker(script);
			}

		}
	};

	toggle_wait_main();
	dojo.xhrGet(request);
}
