
/* AJAX REQUEST FUNCTIONS BEGIN */


// holds an instance of XMLHttpRequest
var ajax = createXmlHttpRequestObject();
// when set to true, display detailed error messages
var showErrors = false;
var rankPlace = new Array();

/* classes */
var searchItem;


function init () {

	/* suggestion */
	searchItem = new suggestion ('searchItem');
	searchItem.setDefaultText('דוגמא: חלב');
	togglePanel();
	drag_drop();
	floating_cart();
}

// creates an XMLHttpRequest instance
function createXmlHttpRequestObject() {
  // will store the reference to the XMLHttpRequest object
	var xhr;
	// this should work for all browsers except IE6 and older
	try {
		// try to create XMLHttpRequest object
		xhr = new XMLHttpRequest();
	}
	catch(e) {
		// assume IE6 or older
		var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
                                    "MSXML2.XMLHTTP.5.0",
                                    "MSXML2.XMLHTTP.4.0",
                                    "MSXML2.XMLHTTP.3.0",
                                    "MSXML2.XMLHTTP",
                                    "Microsoft.XMLHTTP");
		// try every id until one works
		for (var i=0; i<XmlHttpVersions.length && !xhr; i++) {
			try {
				// try to create XMLHttpRequest object
				xhr = new ActiveXObject(XmlHttpVersions[i]);
			}
			catch (e) {} // ignore potential error
		}
	}
	// return the created object or display an error message
	if (!xhr)
	displayError("Error creating the XMLHttpRequest object.");
	else
	return xhr;
}

var requestCache = new Array();
// Keap request in cash
function sendRequest(request, from) {

	// path to PHP request handler
	var requestPath = 'request.php?request='+from+'&';
	// only continue if xmlHttp isn't void
	if (ajax) {
		// if we received non-null parameters, we add them to cache in the
		// form of the query string to be sent to the server for validation
		if (typeof request != 'undefined') {
			requestCache.push(new Array(requestPath + request, from));
		}
		// try to connect to the server
		try {
			// continue only if the XMLHttpRequest object isn't busy
			// and the cache is not empty
			if ((ajax.readyState == 4 || ajax.readyState == 0)
			&&  requestCache.length > 0)
			{
				// get a new set of parameters from the cache
				var sendCache = requestCache.shift();
//				document.getElementById("msg").innerHTML = requestCache;
				// make a server request to validate the extracted data
				ajax.open("GET", sendCache[0], true);
				ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				ajax.send(null);
				ajax.onreadystatechange = function() {
				if (ajax.readyState == 4 && ajax.status == 200) {
					try {
						returnResponse (sendCache[1]);
					}
						catch (e){}
					}
				}
			}
		}
		catch (e) {
			// display an error when failing to connect to the server
			displayError(e.toString()); //$subcat
		}
		if (requestCache.length != 0) {
			setTimeout('sendRequest()', 500);
		}
	}

	// function that process the response
	function returnResponse (sender) {

		// retrieve the server's response
		var response = ajax.responseText;
		// server error?
		try {
			if (response.indexOf("ERRNO") >= 0
				|| response.indexOf("error") >= 0
				|| response.length == 0)
			throw (response.length == 0 ? "Void server response." : response);
		} catch(e) {
			if (showErrors == true)
				alert('ERROR' + response);
		}

		switch (sender) {

			case 'selectLocation':
				document.getElementById("location").innerHTML = response + '&nbsp;&nbsp;&nbsp;<a href="javascript:location.reload(true)"><b>רענן דף</b></a>';
				break;

			case 'CartHandling':
				if (response != "") {
					if ($(response).filter("#response_div").size()>0){
						var items_div = $(response).filter("#response_div").html();
						$("div#cart-products").html(items_div);
						
						if ($(response).filter("input#title").size() > 0) {
							var title = $(response).filter(":input[id=title]").attr("value");
							$("td[id=cart_count]").html("<strong>"+title+"</strong>");
						}
						else {
							var new_quantity = $(response).filter(":input[class=cart_count]").attr("value");
							$("td[id=cart_count]").html("<strong>" + new_quantity + " מוצרים בסל " + "</strong>");
						}
					
						break;
					}
					//save form
					if ($(response).filter("#save_form").size()>0){
							if ($("#save_form").size()==0){
								$(response).insertBefore("div#cart-products");
								$("td[id=cart_count]").html("<strong>שמור סל</strong>");
								$("div#favorites").remove();
							} else  $("#save_form").remove();
						break;
					}
					//login form
					if ($(response).filter("#login_form").size()>0){
						$("div#cart-products").html(response);
						break;
					}
					//favorites
					if ($(response).filter("div#favorites").size()>0){
						if ($("div#favorites").size() == 0) {
							$("#save_form").remove();
							$(response).insertBefore("div#cart-products");
							$("td[id=cart_count]").html("<strong>סלים שמורים</strong>");
							break;
						}
						else {
							$("div#favorites").remove();
						}
					}
				}
				break;

			case 'quickCompare':
				if (response != "") {
					$(response).find("tr[id=prices] td").each(
						function(i){
							$("td[id=price"+i+"]").show().html("₪"+$(this).text());
						});
					$(response).find("tr[id=stores] td").each(
						function(i){
							$("td[id=store"+i+"]").show().html($(this).text());
						});
				} else {
					for (var i=0; i<3; i++){
						$("td[id=price"+i+"]").html("&nbsp;");
						$("td[id=store"+i+"]").hide();
					}
				}
				break;

			case 'detail':
				document.getElementById("item-details").innerHTML=response;
				break;

			case 'searchItem': {
				// retrieve the document element
				searchItem.getResponse(ajax.responseXML.documentElement);
				break;
			}

			case 'rank': {

				var place = rankPlace.shift();
				if (ajax.getResponseHeader("Content-Type") == 'text/xml') {
					response = ajax.responseXML;
					var yes = response.getElementsByTagName("yes")[0].firstChild.data;
					var no = response.getElementsByTagName("no")[0].firstChild.data;
					var message = response.getElementsByTagName("message")[0].firstChild.data;

					document.getElementById("pluses" + place).innerHTML = yes;
					document.getElementById("minuses" + place).innerHTML = no;
					document.getElementById("message" + place).innerHTML = message;

				} else if (response.length>0) {
					document.getElementById("message" + place).innerHTML = response;
				}
				break;
			}

		}
	}
}

/* transforms all the children of an xml node into an array */
function xmlToArray(resultsXml) {
	// initiate the resultsArray
	var resultsArray= new Array();
	// loop through all the xml nodes retrieving the content
	for(i=0; i<resultsXml.length; i++)
		resultsArray[i]=resultsXml.item(i).firstChild.data;
	// return the node's content as an array
	return resultsArray;
}

// function that displays an error message
function displayError($message)
{
	// ignore errors if showErrors is false
	if (showErrors)
	{
		// turn error displaying Off
		showErrors = false;
    // display error message

		alert("Error encountered: \n" + $message);
		// retry validation after 0.5 second
		setTimeout("handleRequestStateChange();", 500);
	}
}


/* AJAX REQUEST FUNCTIONS END */


/* SELECT LOCATION FUNCTION BEGIN */

// Handle Locations
function selectLocation(obj,id) {
	var request = new String();

	switch (obj.name) {
	case 'remove':
		request = 'remove=' + id;
	  break;
	case 'city':
	case 'quarter':
		request = obj.name + '=' + obj.options[obj.selectedIndex].value;
		break;
	}

	// send the request
	sendRequest(request, 'selectLocation');
}

/* SELECT LOCATION FUNCTION END */


/* CART HANDLING BEGIN */

// the function handles the validation for any form field
function CartHandling (act, item_id, quantity, from) {
	var request = new String();

	// if we received non-null parameters, we add them to cache in the
	// form of the query string to be sent to the server for validation
	if (typeof act != 'undefined') {
		if (act == 'ChangeQuantity') {
			if (document.getElementById('quantity'+item_id)){
				quantity = document.getElementById('quantity'+item_id).value;
				quantity = parseInt(quantity);
				item = document.getElementById('item'+item_id);
				item.className+= " incart";
			}
		}
		else if (act == 'AddItem') {
			if (document.getElementById('quantity'+item_id)){
				changeIn = document.getElementById('quantity'+item_id);
				val = parseInt(changeIn.value);
				val = (val + quantity);
				if (val>0) changeIn.value = val;
			}
			var quantity_input = $(":input[id=quantity_text-"+item_id+"]");
			if (quantity_input.size()>0){
				var oldvalue =  parseInt(quantity_input.attr("value"));
				var newval = !isNaN(oldvalue) ?  (oldvalue+parseInt(quantity)) : 1;
				if (newval==0) newval=1;
				quantity_input.attr("value", newval);
			}
			if (from == "incart_add" || from == "mainlist"){
				var oldvalue =  parseInt($("#incart_input-"+item_id).attr("value"));
				var newval = oldvalue+quantity;
				$("#incart_input-"+item_id).attr("value",newval);
			}

		}
		else if (act=='DeleteItem') {
			if (document.getElementById('quantity'+item_id)){
				document.getElementById('quantity'+item_id).value=1;
			}
			$("div[id=item"+item_id+"]").removeClass("incart");
			$("div[id=quantity-"+item_id+"]").hide();
			$(":input[id=quantity_text-"+item_id+"]").attr("value","NaN");
			$("a[id=add_link-"+item_id+"]").show();
		}
		
		else if (act=='CleanCart') {
			$("div[id^=item]").removeClass("incart");
			$("div[id^=quantity-]").hide();
			$(":input[id^=quantity_text-]").attr("value","NaN");
			$("a[id^=add_link-]").show();
		}
		else if (act=='OutputSavedCarts') {
			//
		}
		else if (act=='SaveForm') {
			$("#title_bar").data('title','מועדפים')
		}
		else if (act=='SaveCart') {
			item_id = document.getElementById('CartNameInput').value;
			$("<label id='save_ok'>הסל נשמר בהצלחה!</label>").insertBefore("#save_form");
			$("#save_form").remove();
			setTimeout(function(){$("label#save_ok").remove()},3000);
		}
		else if (act=='OutputHistory') {
			//
		}
		else if (act=='undoDeleteItem') {
			//
		}
		else if (act=='addToActiveCart') {
			$("td#reAdd-" + item_id).html("<img src='images/ok.png'/> המוצר התווסף בהצלחה!");
		}
		else if (act=='deleteSavedCart') {
			$("select#favorite_carts option:selected").remove();
			$("select#favorite_carts option:first").attr("selected","true");
			$("span#options_links").remove();
		}
		else if (act=='ActiveCart'){
			//
		}

		request = 'action=' + act + '&item_id=' + item_id + '&quantity=' + quantity + '&from=' + from;
		// send the request
		sendRequest(request, 'CartHandling');

		sendRequest('','quickCompare');
	}
}

/* CART HANDLING END */

/* ITEM DETAIL BEGIN */

// the function handles the validation for any form field
function getDetail (obj) {
	var request = obj.getAttribute('value');
	// send the request
	sendRequest(request, 'detail');
}

/* ITEM DETAIL END */


function explainCommand (text) {

$("td.right").text(text);

//document.getElementById('explain-command').innerHTML = text;
}


/* EXPAND COLLAPSE AREA FUNCTIONS BEGIN */


function togglePanel() {

	// plus minus categories menu
	$("img[class^=pm]").click(
	function()
	{
		$(this).siblings("ul").slideToggle("fast");
		if ($(this).attr("src") == "images/toggle_minus.gif")
			$(this).attr("src","images/toggle_plus.gif");
		else
			$(this).attr("src","images/toggle_minus.gif");

	});

	// more or less products
	$("li[class^=ml]").click(
	function() {
		var li_div = $(this).prevAll("li[class=more_li]:first");
		li_div.children("div:first").slideToggle("fast");
		if ($(this).attr("class")=="ml-expand")
		{
			$(this).hide();
			$(this).siblings(".ml-collapse").show();
		}
		else {
			$(this).hide();
			$(this).siblings(".ml-expand").show();

		}
	return false;
	});

	// filters sliding selecting
	$(".filter-panel").hide();

	$("a[id^=f]").bind("click",  function () {

	if ($(".filter-panel").css("display") == "none")
	{
		$("div[class^=filter]").slideDown("fast");
		var id = $(this).attr("id");
		$("p[class=filter-name][id!=" + id + "]").css({'color': '#666', 'text-decoration': 'none'});
		$("p[id=" + id + "]").css({'color': '#f09e36'});
	}
	else
	{

		$("div[class^=filter]").slideUp("fast");
	}
	return false;
	});

	var search_list = $("#searchItem-suggestion ul");

	search_list.bind('change_size',function(){
		if ( search_list.height() > 210 ){
			search_list.css("height","210");
			search_list.css("overflow-y","scroll");
		}
		else {
			search_list.height("");
			search_list.css("overflow-y","");
			search_list.css("overflow","auto");
		}

	 });

	search_list.watch("display",function(){
		if (search_list.css("display")=="block") {
			search_list.trigger('change_size');
		}
	});
}


// Rank function sends request to ajax function
function rank(what, rankfor, id)
{
	rankPlace.push(id);
	var req = "rank=" + what + "&rankfor=" + rankfor + "&id=" + id;
	sendRequest(req, 'rank');
}


//DRAG-DROP Function

function drag_drop()
{
	$(function() {
	var $cart = $(".cart");
	var $img = $(".item-picture");
	$img.css("z-index","700");

	//cursorAt: {cursor: 'move', top: 45, left: 45}
	$img.draggable({helper: 'clone', scroll: false });

	$cart.droppable({
		greedy: true,
		hoverClass: 'drophover',
		activeClass: 'activeCart',
		accept: '.item-picture',
		drop: function(ev, ui) {
			var productid = ui.draggable.parent().parent().attr("id");
			productid = parseInt(productid.substring(5, productid.length+1));
			if ($("a#add_link-"+productid).size()>0)
				$("a#add_link-"+productid).click();
			else
				CartHandling('AddItem', productid, 1 );
		}
	});

	});
}


/*
//Deleting from cart using drag-drop
function drag_drop_delete(id) {

	var $thumbnail = $("#" + id);
	var $droparea = $("div[id=content]");


	$thumbnail.draggable({revert: 'invalid', scroll: false, containment: 'none'});

	$droparea.droppable({
			accept: '.thumbnail',
			drop: function(ev, ui) {
				var id = ui.draggable.attr("id");
				CartHandling('DeleteItem', id);
				}
	});
}
*/

function maximize_cart(from){

	var products = $(".incart_items");

	if (products.css("overflow-y") == "scroll"){
		products.css("overflow","visible");
		var rows = $("tr.row").size()
		var height = rows * 100 + 5 + "px";
		products.height(height);
		$("table[class=products]").css({"margin-right": "18px"});
	}else{
		products.css("overflow-y", "scroll");
		products.css("overflow-x", "hidden");
		$("table[class=products]").css({"margin-right": "0px"});
		products.height("120px");
	}
}


function rank_message_over(obj,msg){

	$(obj).nextAll("label[id^=message]:first").hide();

	if ($(obj).attr("id")=="yes")
		$(obj).nextAll("label[id^=overm]:first").text(msg);
	else
		$(obj).nextAll("label[id^=overm]:first").text(msg);
}

function rank_message_out(obj){
	$(obj).nextAll("label[id^=overm]:first").text("");
	$(obj).nextAll("label[id^=message]:first").show();
}

function zoom_image(id,event){
	$("div.zoom_image").remove();
	var img_src = "images/products/"+id+"-big.jpg";
	
	var top = (event.pageY) ? (event.pageY - 35) : (parseInt(window.event.clientY) + $(document).scrollTop() - 35);
	var left = (event.pageX)? (event.pageX + 20) : (parseInt(window.event.clientX) + $(document).scrollLeft() + 20);	

	var image_window = $("<div class='zoom_image' style='background: white; position: absolute; border: solid 2px; z-index:4; top:"+ top + "px; left:"+ left + "px;'></div>");
	image_window.append("<img src='images/close.png' class='close_img' /><br/>");
	image_window.append("<img src='" + img_src + "' class='close_img' />");
	image_window.appendTo("body");
	
	$(".close_img").click(function(){
		$("div.zoom_image").remove();
	});
	
}


function floating_cart(){

	//get original cart header content
	var tablecont = $("table.cartop").html();

	//create new table inside floating div
	$("#cart_header_floating").append($("<table style='width:600px' class='cartop'></table>"));

	var table_cart = $("#cart_header_floating table[class=cartop]");

	//put original content in new table
	table_cart.html(tablecont);

	//create tr for dragging items to here
	table_cart.append($("<tr style='background-color:white'><td colspan='7'><strong>גרור מוצרים לכאן</strong></td></tr>"));

	//background-color of tr with prices white
	$("#cart_header_floating table[class=cartop] tr:first").css("background-color","white");

	//clicking the icons will scroll the page to the top
	table_cart.find("td.space img").bind('click',
	function(){
		$(document).scrollTop(0);
	});

var floating_menu=$("#cart_header_floating");
$(function(){
	$(window).scroll(function() {
			if ($(document).scrollTop() > 140){
				floating_menu.appendTo("div[id=main]");
				floating_menu.css({'display':'block','position':'fixed','top':'0px', 'left': 'auto', 'right': 'auto'});
				var scrollTop = $(document).scrollTop()+"px";
				floating_menu.css({_top: scrollTop});
			}
			else {
				floating_menu.hide();
			}
	});
	
});
}

function add_item_toggle(obj,id){

CartHandling('AddItem',id,1);

$(obj).hide();
$("div#quantity-"+id).show();

$("div[id=item" + id + "]").addClass("incart");
}

//shows options after saved cart was chosen
function show_favorites_list_options(obj){

	var selected_id = $("#favorite_carts :selected").attr("value");
	var selected_name = $("#favorite_carts :selected").text();
	if (selected_id!=0){
		CartHandling('savedCartArray',selected_id); //show temp saved cart
		$("span#options_links").remove();
		var options = $(" <span id='options_links'></span");
		options.append("&nbsp;<img id='use' style='cursor:pointer' src='images/ok.png'/>&nbsp;");
		options.append("<img id='delete' style='cursor:pointer' src='images/delete.png' />");
		options.appendTo("div#favorites");

		$("img#use").click(function(){
			CartHandling('outputSavedCart', selected_id);
			$("div#favorites").remove();
		})

		$("img#use").hover(function(){
			$("span#options_links").append("<label> הפוך לסל הפעיל </label>");
		},function(){$("span#options_links label").remove()});

		$("img#delete").click(function(){
			CartHandling('deleteSavedCart',selected_id);
		})

		$("img#delete").hover(function(){
			$("span#options_links").append("<label> מחק סל </label>");
		},function(){$("span#options_links label").remove()});

	} else $("span#options_links").remove();

}


//user opinion beta
var default_string = 'כתוב דעתך על האתר...';
function opinion_init(obj){
	if ($(obj).val() == default_string) 
		$(obj).val('');
	else if ($(obj).val() == '' ) 
		$(obj).val(default_string);
}

function submit_opinion(message, obj){
	var message = message;
	if (message != default_string) {
		$(obj).ajaxStart(function(){
			$(this).attr('disabled', 'true')
		});
		$.get('functions/sendOpinion.php', {
			message: message
		}, function(){
			$('#opinion textarea').val('דעתך נשלחה, תודה!');
			setTimeout(function(){
				$('#opinion textarea').val(default_string);
				$(obj).attr('disabled', '');
			}, 3000);
		});
	}	
}


/*function ref(instance_or_id) {
	return(typeof(instance_or_id)=="string")?document.getElementById(instance_or_id):instance_or_id;
}

function togglePanel(panel) {
	if(isPanelExpanded(panel)) {
		collapsePanel(panel);
	}else {
		expandPanel(panel);
	}

	function isPanelExpanded(panel){
		return hasClass(panel,'expanded');
	}

	function hasClass(element,_className){
		if(!element){
			return false;
		}
		var upperClass=_className.toUpperCase();
		if(element.className){
			var classes=element.className.split(' ');
			for(var i=0;i<classes.length;i++){
				if(classes[i].toUpperCase()==upperClass){
				return true;
				}
			}
		}
		return false;
	}

	function expandPanel(panel){
		if(!isPanelExpanded(panel)){
		addClass(panel,'expanded');
		fireInlineEvent(panel,'expanded');
		}
	}

	function addClass(element,_class){
		if(!hasClass(element,_class)){
		element.className+=element.className?(" "+_class):_class;
		}
	}

	function collapsePanel(panel){
		if(isPanelExpanded(panel)){
		removeClass(panel,'expanded');
		fireInlineEvent(panel,'collapsed');
		}
	}

	function getClassList(element){
		if(element.className){
		return element.className.split(' ');
		}else{
			return[];
		}
	}

	function removeClass(element,_class){
		var upperClass=_class.toUpperCase();
		var remainingClasses=[];
		if(element.className){
			var classes=element.className.split(' ');
			for(var i=0;i<classes.length;i++){
				if(classes[i].toUpperCase()!=upperClass){
					remainingClasses[remainingClasses.length]=classes[i];
				}
			}
			element.className=remainingClasses.join(' ');
		}
	}

	function fireInlineEvent(element,eventName){
		var target=ref(element);
		if(target[eventName]==null){
			var attributeName='on'+eventName.toLowerCase();
			var attribute=target.attributes.getNamedItem(attributeName);
			if(attribute){
				target[eventName]=function(){
				eval(attribute.value);
				}
			}
		}
		if(target[eventName])target[eventName]();
	}
}

*/

/* toggle content by changing radio value */
function toggleSet(rad) {
  var type = rad.value;

  $(".search[id!=" + type + "]").css("display" , "none");
  $(".search[id=" + type + "]").css("display" , "block");

  /*for(var k=0,elm; elm=rad.form.elements[k]; k++)
    if(elm.className=='search')
      elm.style.display = elm.id==type? 'block':'';*/
}

/* EXPAND COLLAPSE AREA FUNCIONS END */


(function($){
$.fn.watch = function(prop, func, interval, id) {
 
    if (!interval)
        interval = 200;
    if (!id)
        id = "_watcher";

    this.each(function() {
        var _t = this;
        var el = $(this);
        var fnc = function() {__watcher.call(_t, id) };
        var itId = null;

        var z = el.get(0);                        
        if (typeof(z.onpropertychange) == "object")
           el.bind("propertychange", fnc);
        else if ($.browser.mozilla)
            el.bind("DOMAttrModified", fnc);
        else
            itId = setInterval(fnc, interval);

        el.data(id, { id: itId,
            prop: prop,
            func: func,
            val: prop ? el.css(prop) : null
        });
    });
    return this;
}
$.fn.unwatch = function(id) {
    this.each(function() {
        var w = $(this).data(id);
        $(this).removeData();

        if (typeof (z.onpropertychange) == "object")
            el.unbind("propertychange", fnc);
        else if ($.browser.mozilla)
            el.unbind("DOMAttrModified", fnc);
        else
            clearInterval(w.id);
    });
    return this;
}
function __watcher(id) {
    var el = $(this);
    var w = el.data(id);
    
    if (w.prop) {
        var newVal = el.css(w.prop);
        if (w.val != newVal)
            w.val = newVal;
        else
            return;
    }
    if (w.func) {        
        var _t = this;
        w.func.call(_t)
    }
}

})(jQuery);

