﻿function searchform(url, couponContainer, searchContainer, form, format) {
    var $this = this;
    this.url = url;
    this.couponContainer = couponContainer;
    this.searchContainer = searchContainer;
    this.form = form;
    this.sorting = false;
    this.sortby = "";
    this.summary = false;
    this.numberofcoupons = 0;
    this.numberofcategories = 0;
    this.numberofbrands = 0;
    this.numburofaccounts = 0;
    this.couponsareas = "";
    this.categories = "";
    this.pagenumber = 1;
    this.puresearch = false;
    this.format = typeof (format) != 'undefined' ? format : "xml";
	this.combineMultiple = function(array, name) {
		var str = "";
		$.each(array, function(i, field) {
			if (field.name == "geo_area[]") {
				$.get("/ajax/translate.php", { 'phrase_id': field.value }, function(r2){
    				$this.couponsareas = r2;
    			});
			}
			if (field.name === "cat_phrase[]" | field.name === "brd_phrase[]") {
				field.value = field.value.replace("#", "")
				field.value = "#" + field.value;
			}
			if (name == field.name) {
				str = str + encodeURIComponent(field.value) + "|";
			}
		});
		str = str + "|";
		str = str.replace("||", "");
		return str;
	};
	this.getArray = function(array) {
		var arr, x, searchprase, undefarray = false;
		if (array === undefined) { undefarray = true; }
		array = typeof (array) != 'undefined' ? array : $(this.form).serializeArray();
		arr = "";
		searchprase = $('input[name="phrase"]').val();
		if (this.puresearch & searchprase !== "") {
			arr="n=-30&geo_area=1888&";
		} else {
			x = "";
			$.each(array, function(i, field) {
				if (field.name !== x) {
			    	arr = arr + field.name + "=" + $this.combineMultiple(array, field.name) + "&";
				}
				arr = arr.replace('[]', '');
				x = field.name;
			});
		}
		if (this.sorting) {
			arr = arr + "&sort=" + this.sortby;
		}
		if (this.summary) {
			arr = arr + "&summary=1";
		}
		if (!undefarray) {
			arr = arr + "&n=-30";
		}
		if (searchprase !== "") {
			arr = arr + "&phrase=" + searchprase;
		}
		arr = arr + "&p=" + this.pagenumber;
		arr = arr.replace('&&', '&');
		return arr;
	};
	this.parseResult = function(result, callback) {
		if (result === "") {
		    $(this.couponContainer).html('<a style="direction: rtl">לא נמצאו מבצעים</a>');
		    $(this.searchContainer).hide();
		    $(this.couponContainer).fadeIn();
		    $("div.hello-note-box").html('<h2 style="color: white; padding-top: 5px; direction: rtl;">לא נמצאו מבצעים</h2>');
		    callback(true, "success");
	    } else {
			$($this.couponContainer).html(result);
			$($this.searchContainer).hide();
			$($this.couponContainer).fadeIn();
			$("div.hello-note-box").html('<h3 style="color: white; padding-top: 10px; direction: rtl;">' + 'מציג מבצעים מ ' + $this.numberofcategories + ' קטגוריות, באיזורים ' + $this.couponsareas + ', מ ' + $this.numberofbrands + ' מותגים, ' + $this.numberofaccounts + ' חנויות. נמצאו ' + $this.numbarofcoupons + ' תוצאות.' + '</h3>');
			callback(true, "success");
		}
	}
	this.parseSummary = function(result) {
		if (!$.isEmptyObject(result)) {
			$this.numbarofcoupons = result.num_results_total;
			$this.categories = "";
			pagination.next_page_num = result.next_page_num;
			pagination.has_next_page = result.has_next_page;
			pagination.has_prev_page = result.has_prev_page;
			pagination.num_pages = result.num_pages;
			pagination.num_results_shown = result.num_results_shown;
			pagination.num_results_total = result.num_results_total;
			pagination.prev_page_num = result.prev_page_num;
			pagination.this_page_num = result.this_page_num;
			$.each(result.category_phrase_ids, function(i, category_id) {
				$this.numberofcategories = i+1;
			});
			$.each(result.brand_phrase_ids, function(i, brand_id) {
				$this.numberofbrands = i+1;
			});
			$.each(result.account_ids, function(i, account_id) {
				$this.numberofaccounts = i+1;
			});
			return true;
		} else {
			return false;
		}
	};
	this.getSummary = function(arr, callback) {
		this.summary = true;
		if (arr === undefined) {
			arr = this.getArray();
		} else {
			arr = this.getArray(arr);
		}
		$.get("/ajax/summary.php", arr, function(result) {
			if($this.parseSummary(result)) {
				$this.summary = false;
				callback(true, "Summary parsed");
			} else {
				$this.summary = false;
				callback(false, "Summary not parsed");
			}
		}, "json").error(function(error) { callback(false, error.statusText) });
	};
	this.ajaxForm = function(arr, callback) {
		if (arr === undefined) {
			arr = this.getArray();
		} else {
			arr = this.getArray(arr);
		}
		$.get(this.url, arr, function(result) {
			$this.parseResult(result, function(state, msg) {
				callback(state, msg);
			});
		});
	};
	this.executeForm = function() {
		$(this.searchContainer).hide();
		$('input:checkbox,input:radio').click(function() {
			var customarray = undefined;
			var pscheckbox = $("#puresearch").is(':checked');
			if (pscheckbox) { $this.puresearch = true; } else { $this.puresearch = false; }
			if (!$this.sorting) { $("div.sort-by-bg-on").attr("class", "sort-by-bg"); }
			if ($(this).attr("id") == "filtertrigger") { customarray = profiles.filtersarray; }
			$($this.couponContainer).hide();
			$($this.searchContainer).fadeIn();
			// $(".input-search").val('');
			$this.getSummary(customarray, function(fstate, fmsg) {
				if (!fstate) {
					log(fmsg);
				}
				if (fmsg == "parsererror") {
					$("div.paging-box").fadeOut();
				} else {
					$("div.paging-box").fadeIn();
				}
				$this.ajaxForm(customarray, function(state, msg){
					if(state) {
						pagination.executeAll();
						$this.pagenumber = 1;
					} else {
						log(msg);
					}
				});
			});
		});
	};
}

