var Truck = (typeof(tm) != 'undefined') ? Truck : {
	registry : {},
	set : function(name, object)
	{
		this.registry[name] = object;
	},
	get : function(name)
	{
		return this.has(name) ? this.registry[name] : false;
	},
	has : function(name)
	{
		return this.registry.hasOwnProperty(name);
	},
	charCode : function getCharCode(event)
	{
		return event.charCode || event.keyCode || event.which || 0;
	},
	log : function () {
		if ((typeof(console) != 'undefined') && (typeof(console.log) == 'function')) {
			console.log(arguments);
		} else if (window.opera && opera.postError) {
			opera.postError(arguments);
		};
	},
	widget: {},
	helpers : {
		/**
		 * Возвращает целое число в удобном для человека виде - с пробелами
		 */
		formatNumber: function (number) {
			if (!number) {return '';}
			var s = number.toString();
			var r = '';
			for ( i = 0, l = s.length; i<l; i++) {
				r = r + (((((l-i) % 3) == 0) && (i != 0)) ? ' ' : '') + s.charAt(i);
			};
			return r;
		},
		/**
		 * Возвращает дату и время в нормальном виде
		 */
		formatDate: function(timestamp, dateOnly){
			var today = new Date();
			var date = new Date(timestamp * 1000);
			var months = ["января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря"];;
			var result = "";
			if(today.getDate() != date.getDate() || today.getMonth() != date.getMonth() || today.getFullYear() != date.getFullYear())
				result = date.getDate() + " " + months[date.getMonth()];
			if(today.getFullYear() != date.getFullYear())
				result += " " + date.getFullYear();
			if(!dateOnly) {
				if (result) result += ", ";
				result += "в " + tm.helpers.addZero(date.getHours(), 2) + ":" + tm.helpers.addZero(date.getMinutes(), 2);
			}
			return result;
		},
		/**
		 * Добавляет нули перед числом до тех пор, пока оно не достигнет нужной длины
		 */
		addZero: function(number, len) {
			var s = number.toString();
			while (s.length < len) s='0'+s;
			return s;
		}
	}
};
Truck.helpers.in_array = function(array, value) {
    for (var i in array) {
        if (array[i] == value) return true;
    }
    return false;
}
Truck.widget.Slider = function()
{
	// контейнер
	var $ears = $("#phone-slider-container");
	// количество прокручиваемых элементов за раз
	var count = 4;
	// количество элементов
	var n = $ears.children("div").length;
	if (n < 5) return;
	// ширина элемента
	var wEl = $ears.find("*:first").width();
	// теоретическая ширина контейнера
	var w = wEl * n; // +wEl — хак, 27/4
	// реальная ширина
	var wReal = w+wEl*(count*2);
	// ширину всех элементов (с дублями) присваиваем контейнеру
	$ears.width(wReal+"px");
	// выбираем count элементов с начала и с конца
	var le = $ears.children("div:lt("+(count)+")");
	var re = $ears.children("div:gt("+(n-1-count)+")");
	// вставляем элементы сначала в конец и с конца в начало
	le.clone().appendTo($ears);
	re.clone().prependTo($ears);

	$ears.css("left",(wEl*-4)+"px");

	// навешиваем события на кнопки
	//$("#ears-btn-prev").click(ears.prev);
	//$("#ears-btn-next").click(ears.next);

	this.next = function() {
		if (n < 5) return;
		//$ears.stop(true,true);
		if (this.run) return;
		this.run = true;
		var l = parseInt($ears.css("left")) || 0;
		if (l <= w*-1) {
			$ears.css("left","0px");
			this.run = false;
			this.next();
			return;
		}
		else l = l - wEl*4;
		l = l.toString() + "px";
		$ears.animate({left: l}, 1000, "easeInOutQuad", function(){slider.run = false} );
		return;
	}
	this.prev = function() {
		if (n < 5) return;
		//$ears.stop(true,true);
		if (this.run) return;
		this.run = true;
		var l = parseInt($ears.css("left")) || 0;
		if (l >= 0) {
			$ears.css("left",(w*-1)+"px");
			this.run = false;
			this.prev();
			return;
		}
		else l = l + wEl*4;
		l = l.toString() + "px";
		$ears.animate({left: l}, 1000, "easeInOutQuad", function(){slider.run = false} );
		return;
	}
}

$(document).ready(function()
{
	if ($("#phone-slider-container").length) {
		slider = new Truck.widget.Slider();
	}

	if ($("#order-container, #fn-basket").length) {
		order = new Basket();
	}

	if ($("#make-autocomplete").length) {
		_brands_autocomplete();
	}
	
	if ($("#content table.orderlist").length)
		$("#content table.orderlist tr").filter(
		function (index) {
			return index % 2;
		}).addClass("x2");
		
	if ($("#mapbox").length)
		$("#mapbox").mouseover(function(){
			$("#mapbox img").stop();
			$("#mapbox img").animate({
				width: "385px",
				height: "269px"
			}, 500 ).attr("src", "/img/map_large.png");

		}).mouseout(function(){
			$("#mapbox img").stop();
			$("#mapbox img").animate({
				width: "190px",
				height: "135px"
			}, 500 ).attr("src", "/img/map_small.png");
		});

	$("#imei-digits").each(function(){
		$(this).children("input").keyup(function(){
				if (this.value != "") $(this).next("input").focus();
			}).focus(function(){
				$(this).select();
			});
	});
	$("#acc-numb, #sort-code").each(function(){
		$(this).find("input").keyup(function(){
				if (this.value != "") $(this).parent().next("div").children("input").focus();
			}).focus(function(){
				$(this).select();
			});
	});

	//$("div.btn-redbut").hover(function(){$(this).addClass("btn-redbut-hover")},function(){$(this).removeClass("btn-redbut-hover")});
	$('div.btn-redbut').live('mouseover mouseout', function(event) {
		if (event.type == 'mouseover') {
			$(this).addClass("btn-redbut-hover");
		} else {
			$(this).removeClass("btn-redbut-hover");
		}
	});
	$(".checkboxLine").hover(function(){$(this).toggleClass("checkboxLine-hover")},function(){$(this).toggleClass("checkboxLine-hover")});
	$(".btn_question").hover(function(){$(this).toggleClass("btn_question-hover")},function(){$(this).toggleClass("btn_question-hover")});
	if (jQuery.browser.webkit && navigator.userAgent.indexOf("Chrome") == -1) {
		$(".mi-select").parent(".m-input").addClass("hack-safari-select");
	}
	$("div.tooltip-hover").each(function(){
		$(this).hover(function()
		{
			var self = this;
			window.tth_flag = window.setTimeout(function()
			{
				var j = $("#tooltipbox-"+self.innerHTML);
				j.css({top: $(self).offset().top-30,
					  left: $(self).offset().left+40
					});
				if (jQuery.browser.msie) j.show();
				else j.fadeIn(300);
			},
			300);
		},
		function(){
			window.clearTimeout(window.tth_flag);
			var j = $("#tooltipbox-"+this.innerHTML);
			if (jQuery.browser.msie) j.hide();
			else j.fadeOut(300);
		});
	});

	if ($("#register-reffer").length)
	{
		$("#register-reffer").change(function(){
			if (this.value != "Other") $("#form-reffer-manual").slideUp();
			else
				$("#form-reffer-manual").insertAfter($(this).parents(".element")).slideDown().show("highlight");
		});
	}
	$(".iSelect").click();

	checkDisable();
});

//TODO: учитывать padding и абсолютно позиционированные элементы вне блока
function checkDisable() {
	$(".disable").each(function(){
		disable($(this));
		//jt.prepend('<div class="disable_container" style="height:'+jt.height()+'"><img src="/img/spacer.gif" width="100%" height="100%"></div>');
	});
}
function undisable(jt) {
	jt.removeClass("disable");
	jt.children(".disable_container").hide().remove();
}
function disable(jt) {
	var color;

	//if (arguments.length == 1) color = "gray";
	//else color = arguments[0];

	jt.addClass("disable");
	//jt.addClass("disable-"+color);
	//if ($("div.title",jt).length == 1)
	//	jt.prepend('<div class="disable_container pngfix" style="height:'+(jt.height()+40)+'px;margin-top:-30px"><img src="/img/spacer.gif" width="100%" height="100%"></div>');
	//else
		jt.prepend('<div class="disable_container pngfix" style="height:'+jt.height()+'px"><img src="/img/spacer.gif" width="100%" height="100%"></div>');
}
function open_terms_window() {
	//apply = window.open("/terms-and-conditions/?print","Loading",'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width=550,height=450');
	_terms_popup();
	return false;
}

function sidebarSearchChange(t) {
	if (phones[t.value]) {
		var html = '<option value="0"></option>';
		$.each(phones[t.value], function(id,model){
			html += '<option value="'+id+'">'+model+'</option>';
		});
		$("#model").html(html);
	} else $("#model").html("");
}
function sidebarSearchSelect(t) {
	var phoneId = t.value;
	if (t.value != 0) window.location = "/process/"+phoneId+"/";
}

function viewBox(el, text) {
	var data = {};
	data.working = "<p><b>working</b> - each mobile handset should:</p><ul><li>switch on & off</li><li>not be broken or liquid-damaged</li><li>be fully functional (general wear and tear is acceptable)</li><li>include the battery (if you are missing the charger or memory card that's fine)</li><li>screen should be working</li></ul><p><b>not-working</b> - each mobile handset should:</p><ul><li>include its battery (if you are missing the charger or memory card that's fine)</li><li>be fully intact - not in parts</li></ul><p>examples: broken/bleeding LCD (screen), blank display, no power up, faulty touch screen, etc.</p>";

	var box = $("<div class='tooltip300 sbox pngfix'><div class='bottom pngfix'><div class='bg pngfix'></div></div></div>");
		box.find(".bg").html('<div class="arrow pngfix"></div>'+data[text]);
		box .addClass("tooltip")
			.css({top: el.offset().top-30,
				left: el.offset().left+40
			   })
			.appendTo("body");
			/*.idle(3000)
			.fadeOut("slow", function(){ $(this).remove(); });*/
	}

$.fn.idle = function(time)
  {
      var o = $(this);
      o.queue(function()
      {
         setTimeout(function()
         {
            o.dequeue();
         }, time);
      });
      return this;
  }
function fn_profile_bankdetail()
{
	if (!window.order) order = new Basket();
	order.obj = $("#btn_bankinfosave");

	var bankCheck = order.bankdetailCheck();

	if (!bankCheck.error) {
		if (window.pbdUpdateClick) return;
		window.pbdUpdateClick = true;
		order.obj.addClass("button_disable");
		order.request({method: "profileBankAccDetailUpdate", accname: $("#acc-name").val(), bankname: $("#bank-name").val(), accnumb: bankCheck.accnumb, sortcode: bankCheck.sortcode}, function(data) {
			order.obj.removeClass("button_disable");
			window.pbdUpdateClick = false;
			Truck.get("window").show('<div class="process-imeicheck win-success"><h2>Successful!</h2><p>Your bank details information has been updated.</p><div class="btn-multi btn-redbut" onclick="Truck.get(\'window\').hide();"><div><div>Ok</div></div></div></div>');
		});
	}
}

function Basket() {
	var obj = $("#order-container");
	var ajax_url = "/ajax/2.0/";
	this.error_obj = obj;
	this.working = -1;
	this.money = "cash";

	if (window.bpi) {
		this.working = bpi.working;
		this.money = bpi.money;
	}

	if ($("#basket-toggle").length)
	{
		$("#basket-toggle").toggle(function(){
			$(this).addClass("basket-button-hide").prev().effect("blind");
		}, function(){
			$(this).removeClass("basket-button-hide").prev().show("blind");
		}).css("cursor","pointer").hover(function(){$(this).toggleClass("basket-button-hover");});
	}
	$(".pi-working-status .pi-working, .pi-working-status .pi-working-not",obj).hover(function(){$(this).addClass("pi-working-hover");},function(){$(this).removeClass("pi-working-hover");});
	$("#order_money div",obj).hover(function(){$(this).addClass("checked");},function(){$(this).removeClass("checked");});

	/*
	 * iSelect
	 */
	if ($(".iSelect").length)
	{
		var $select = $(".iSelect");
		$select.hover(function(){
			$(".iSelect-hover",$select).stop().fadeTo(200, 1);
			$("span",$select).stop().fadeTo(300, 0.5);
		}, function () {
			$(".iSelect-hover",$select).stop().fadeTo(200, 0);
			$("span",$select).stop().fadeTo(300, 1);
		});
		$select.toggle(function(){
			$(".iSelect-point",$select).attr("style","").switchClass("iSelect-notworking","iSelect-working",300);
			order.setWorking(1);
			$(".pi-phoneprice .price").css("color", "#0093F1");
			$(".iSelect-point span",$select).text("Working");
			$("#pi-working-status-tooltip").unbind('onmouseover').mouseover(function(){tooltip.show('<p><b>Working means that your handset should:</b></p><ul class="mb15"><li>Switch on and off</li><li>Not be broken or have damage from any liquid</li><li>Be fully functional (but don\'t worry, general wear and tear is fine!)</li><li>Include the battery (don\'t worry if it\'s missing the charger or any memory cards)</li><li>Screen should be working</li></ul>');});
		}, function(){
			$(".iSelect-point",$select).attr("style","").switchClass("iSelect-working","iSelect-notworking",300);
			order.setWorking(0);
			$(".pi-phoneprice .price").css("color", "#f00");
			$(".iSelect-point span",$select).text("Not Working");
			$("#pi-working-status-tooltip").unbind('onmouseover').mouseover(function(){tooltip.show('<p><b>Not-working means that your handset should at least:</b></p><ul><li>Include it\'s battery (don\'t worry if it\'s missing the charger or any memory cards)</li><li>be fully intact i.e. Not in parts</li></ul><p class="small">Examples of things that are acceptable: Broken/bleeding LCD Screen, blank display, no power up, faulty touch screen etc.</p>');});
		});
	}
	$("#imei-digits .btn_question").unbind('onmouseover').mouseover(function(){tooltip.show('<p class="small">If you can\'t find your IMEI number, try removing the back casing and battery of your handset. It should be printed on the phone near the sim-card input.</p>');});

	this.request = function(data,callback) {
		$.post(ajax_url, data,
			function(data) {
				if (data.status == "success") {
					callback(data);
				} else if (data.status == "error" || data.status == "alert") {
					order.errorView(order.error_obj,data.message);
				} else {
					order.errorView(order.error_obj,"Unknown error");
				}
		}, "json");
	}
	this.addItem = function() {
		Flybox.preloader.show();
		order.error_obj = $("#fn-buttons-add");
		this.request({method: "basketAdd", id: phoneInfo.id, working: this.working, money: this.money, imei: this.imei}, function(data) {
			Flybox.hide();
			if (!data.imeicheck) {
				//order.errorView($("#imei-digits input:first"), data.imeimessage);
				Truck.get("window").show('<div class="process-imeicheck"><h2>Woops!</h2><p>This handset has been reported as lost/stolen so unfortunately we\'re not able to proceed with your order.</p><p>Please contact your network service provider for help in resolving this issue.</p><div class="btn-multi btn-redbut" onclick="Truck.get(\'window\').hide();"><div><div>Ok</div></div></div></div>');
				/*$("#imei-fucking").text(data.imeimessage).show();
				$("#imei-digits input").keypress(function(){$("#imei-fucking").hide();});*/
			} else {
				$("div.pi-buttons").fadeOut(200);
				$("#fn-buttons-continue").delay(210).fadeIn(300);
				order.renderBasket(data.basket);
				disable($("#order-container div.phone-info"));
			}
		});
	}
	this.renderBasket = function() {
		if (arguments[0]) this.dataBasket = arguments[0];
		var code = '';
		var total = 0;
		$.each(this.dataBasket, function(id,phone){
			total += parseFloat(phone.user_price);
			code += '<div id="'+id+'" class="bphone">';
			code += '<div class="image"><img src="'+phone.image+'" alt="'+phone.phone+'"></div>';
			code += '<div class="phone">'+phone.phone+'</div>';
			code += '<div class="imei"><span>IMEI:</span> '+phone.imei+'</div>';
			code += '<div class="condition"><span>Condition:</span> '+phone.working_text+'</div>';
			code += '<div class="payment"><span>Payment:</span> '+phone.payment+'</div><div class="cl-l"></div>';
			code += '<div class="manage"><a onclick="return order.deletePhone(\''+id+'\', this)" href="#">Remove</a><a href="'+urlStep1+id+'/">Edit</a></div></div>';
		});
		code += '<div class="bphone bphone-total"><span>Total</span> <strong>&pound;'+number_format(total,2)+'</strong></div>';
		$("#fn-basket").html(code);
	}
	this.errorView = function(el, text) {
		$("<span>") .text(text)
					.addClass("tooltip-m")
					.css({top: el.offset().top+el.outerHeight()+1,
					    left: el.offset().left+5,
						width: text.length*8
					   })
					.appendTo("body")
					.idle(3000)
					.fadeOut("slow", function(){$(this).remove();});
	}
	this.setWorking = function(param,t) {
		if (this.working == param) return;
		this.working = param;
		var $boxes = $(".pi-phoneprice, .pi-phonepay, .pi-phoneimei, #pi-buttonset");
		//$(".pi-working-status .pi-working, .pi-working-status .pi-working-not",obj).removeClass("pi-working-selected");
		//$(t).addClass("pi-working-selected");

		$boxes.stop(true,true);

		/*if ($(".pi-phoneprice").css("display") != "none") {
			$boxes.fadeOut(300,function(){
				$(".pi-phoneprice .price span").html(number_format(param ? phoneInfo.prices[0] : phoneInfo.prices[2], 2, '.', ''));
				order.showBoxes();
			});
		}*/
		$(".pi-phoneprice .price span").html(number_format(param ? phoneInfo.prices[0] : phoneInfo.prices[1], 2, '.', ''));

		
		if ($(".pi-phoneprice").css("display") == "none") {
			//$(".pi-phoneprice .price span").html(number_format(param ? phoneInfo.prices[0] : phoneInfo.prices[2], 2, '.', ''));
			this.showBoxes();
		}
		// обновление цен OLD
		//this.updateMoney("cash",param ? phoneInfo.prices[0] : phoneInfo.prices[2]);
		//this.updateMoney("voucher",param ? phoneInfo.prices[1] : phoneInfo.prices[3]);
	}
	this.showBoxes = function()
	{
			$(".pi-phoneprice").slideDown(700,function(){
				//$(".pi-phonepay").slideDown(250,function(){
					$("body:not(:animated)").animate({scrollTop: $("#footer").offset().top-$("#content").height()}, 500 );
					$("html").animate({scrollTop: $("#footer").offset().top-$("#content").height()}, 500 );
					$(".pi-phoneimei").slideDown(250,function(){
						$("#pi-buttonset").fadeIn(500,function(){
						});
					});
				//});
			});
	}
	this.updateMoney = function(money, price)
	{
		$("#fn-phone-payment ."+money+" .text span").html(number_format(price, 2, '.', ''));
		if (price == 0) $("#fn-phone-payment ."+money).hide();
		else $("#fn-phone-payment ."+money).show();
	}
	/* NOT USED NOW */
	this.setMoney = function(param,t) {
		this.money = param;
		$("#fn-phone-payment div",obj).removeClass("pi-working-selected");
		$(t).addClass("pi-working-selected");
	}
	this.addHandset = function() {
		if (this.working == -1) {
			this.errorView($(".pi-working-not",obj),"Please select the working order of your handset");
		} else if (this.money == -1) {
			this.errorView($(".pi-phonepay .checkboxLine:first",obj),"Select payment method please");
		} else if (this.checkImei()) {
			this.addItem();
		}
	}
	this.checkImei = function() {
		var error = false;
		var imei = "";
		$("#imei-digits input").each(function(i,f){
			imei += f.value;
			if (!error && f.value == "") {
				order.errorView($(f), "Please enter your handset's IMEI number!");
				error = true;
			}
			if (!error && isNaN(parseInt(f.value))) {
				order.errorView($(f), "IMEI numbers must not contain letters or symbols");
				error = true;
			}
		});
		if (!error) {
			this.imei = imei;
			return true;
		}
		return false;
	}
	this.deletePhone = function(id, t) {
		this.request({method: "basketDelete", id: id}, function(data) {
			$(t).parents("div.bphone").remove();
			order.dataBasket = data.basket;
			if ($("#fn-basket div.bphone").length < 2) $("#fn-basket").html('<div class="bphone bphone-empty">Your basket is empty.</div>');
			else order.renderBasket();
		});
		return false;
	}
	this.cancelHandset = function(id) {
		disable($("#order-container div.phone-info"));
		undisable($("#"+id));
		$(".pi-buttons").fadeOut(200);
		$("#fn-buttons-continue").delay(210).fadeIn(300);
	}
	this.saveHandset = function(id) {
		if (this.checkImei()) {
			var price = this.working ? phoneInfo.prices[0] : phoneInfo.prices[1];
			this.request({method: "basketEdit", id: id, working: this.working, money: this.money, imei: this.imei, price: price}, function(data) {
				if (!data.imeicheck) {
					//order.errorView($("#imei-digits input:first"), data.imeimessage);
					$("#imei-fucking").text(data.imeimessage).show();
					$("#imei-digits input").keypress(function(){$("#imei-fucking").hide();});
				} else {
					$(".pi-buttons").fadeOut(200);
					$("#fn-buttons-continue").delay(210).fadeIn(300);
					
					order.renderBasket(data.basket);
					disable($("#order-container .phone-info"));
				}
			});
		}
	}
	this.save = function(id) {
		var error = false;
		var imei = "";
		$("#imei-digits input").each(function(i,f){
			imei += f.value;
			if (!error && f.value == "") {
				order.errorView($(f), "Please complete the field above to continue!");
				error = true;
			}
			if (!error && isNaN(parseInt(f.value))) {
				order.errorView($(f), "Value does not appear to be an integer");
				error = true;
			}
		});
		if (!error) {
			this.request({act: "setimei", id: id, imei: imei}, function() {
				$("#imei-box div.button_add-more-handset").removeClass("button_disable");
				undisable($("#holder-box"));
				order.flag_setimei = true;
			});
		}
	}
	this.addMorePhones = function() {
		if (order.flag_setimei) window.location = "/";
	}

	this.confirmProfile = function() {
		if ($("#accept-terms").length && !$("#accept-terms:checked").length)
			order.errorView($("#accept-terms"), "Please accept in order to proceed");
		else
			window.location = "/sell-recycle/mobile-phone/step3/";
	}

	this.bankdetailCheck = function() {
		var error = false;
		var accnumb = "";
		var sortcode = "";
		if ($("#acc-name").val() == "") {
			order.errorView($("#acc-name"), "Please enter the account holder name");
			error = true;
		}
		if ($("#bank-name").val() == "") {
			order.errorView($("#bank-name"), "Please enter the name of Bank");
			error = true;
		}
		$("#acc-numb input").each(function(i,f){
			accnumb += +f.value;
			if (!error && f.value == "") {
				order.errorView($(f), "Please enter a valid account number");
				error = true;
			}
			if (!error && isNaN(parseInt(f.value))) {
				order.errorView($(f), "Field must only contain numbers");
				error = true;
			}
		});
		$("#sort-code input").each(function(i,f){
			sortcode += f.value;
			if (!error && f.value == "") {
				order.errorView($(f), "Please enter a valid sort code");
				error = true;
			}
			if (!error && isNaN(parseInt(f.value))) {
				order.errorView($(f), "Field must only contain numbers");
				error = true;
			}
		});

		return {error: error, accnumb: accnumb, sortcode: sortcode};
	}

	this.goOrder = function() {
		var bankCheck = this.bankdetailCheck();
		if (!bankCheck.error) {
			if (this.orderSend) return;
			disable($("#fn-basket"));
			this.orderSend = true;
			$("#acc-numb-hidden").val(bankCheck.accnumb);
			$("#sort-code-hidden").val(bankCheck.sortcode);
			$("#bank-details-form").submit();
			/*this.request({method: "basketOrder", accname: $("#acc-name").val(), accnumb: bankCheck.accnumb, sortcode: bankCheck.sortcode}, function(data) {
				$("#orderconfirm-orderno").text(data.orderNo);
				$("#orderconfirm").show("slow");
			});*/
		}
	}
}
function _brands_autocomplete()
{
	var $make = $("#make-autocomplete");
	var $model = $("#model-autocomplete");

	function getMakeIdFromName(name) {
		for(var i in _data_brands) {
			if (!_data_brands.hasOwnProperty(i)) continue;
			if (_data_brands[i].v.toLowerCase() == name.toLowerCase()) return _data_brands[i].id;
		}
		return false;
	}
	function getModelIdFromName(name) {
		for(var i in _data_brand_phones[_last_selected_brand_id]) {
			if (!_data_brand_phones[_last_selected_brand_id].hasOwnProperty(i)) continue;
			if (_data_brand_phones[_last_selected_brand_id][i][0].toLowerCase() == name.toLowerCase()) return _data_brand_phones[_last_selected_brand_id][i][1];
		}
		return false;
	}
	function getModelFromName(name) {
		for(var i in _data_brand_phones[_last_selected_brand_id]) {
			if (!_data_brand_phones[_last_selected_brand_id].hasOwnProperty(i)) continue;
			if (_data_brand_phones[_last_selected_brand_id][i][0].toLowerCase() == name.toLowerCase()) return _data_brand_phones[_last_selected_brand_id][i];
		}
		return false;
	}
	function model_focus() {
		$model.prev(".eg").hide();
		clearTimeout(Truck.get("timeout.modelEg"));

		
		var id = getMakeIdFromName($make.val());

		if (window._last_selected_brand_id && _last_selected_brand_id == id) return true;

		if (id) {
			$model.val("").unautocomplete()
				.autocomplete(_data_brand_phones[id],{
					/*formatItem: function(item) {
						return item.v;
					},*/
					resultsClass: "autocomplete-select model-autocomplete",
					minChars: 0,
					max: 300,
					scroll: true,
					scrollHeight: 250,
					matchContains: true
				})
				.result(function(event,item,value) {
					_last_selected_phone = item[1];
					model_search();
				})
				.unbind("focus",model_focus).focus(model_focus);
			$model.unbind("keydown",model_keydown).keydown(model_keydown);
			$model.unbind("keypress",model_keypress).keypress(model_keypress);
			_last_selected_brand_id = id;
		}
		return true;
	}
	function model_search() {
		var model = getModelFromName($model.val());
		if (model) {
//			if (window._last_selected_phone && _last_selected_phone == model[1] && $("#findbox .image img").attr("src") == "/img/nophoto.gif") return;
			var image = "/8mobile-handsets/mobile-phones/8-mobile-"+model[3]+"."+model[2];
			if (window._last_selected_phone && _last_selected_phone == model[1] && $("#findbox .image img").attr("src") == image && $("#findbox .image img").css("display") != "none") return;
			_last_selected_phone = model[1];
			$("#findbox .image img").attr("src", "/img/nophoto.gif");
			$("<img>").load(function(){
				$("#findbox .image img").hide().attr("src", image).attr("alt",model[0]+' – 8 mobile').fadeIn(800);
				$(this).remove();
			}).attr("src", image);
		}
	}
	function model_keydown(){
		clearTimeout(Truck.get("temp.model-autocomplete-timer"));
	}
	function model_keypress(event){
		//console.log(Truck.charCode(event));
			if (Truck.helpers.in_array([13, 37, 38, 39, 40, 27, 45, 33, 34, 35, 36],Truck.charCode(event))) return;

			if (Truck.has("temp.model-autocomplete-value") && Truck.get("temp.model-autocomplete-value") == $model.val()) return;
			Truck.set("temp.model-autocomplete-value",$model.val());

			if ($("#findbox .image img").attr("src") != "/img/select-phone-image.png")
				$("#findbox .image img").fadeOut(function(){$(this).attr("src","/img/select-phone-image.png").fadeIn()});
			if (!window._last_selected_brand_id || $model.val() == "") return;
			Truck.set("temp.model-autocomplete-timer",setTimeout(function(){
				model_search();
			},500));
	}
	(function($) {
		$make.autocomplete(_data_brands,{
			formatItem: function(item) {
				return item.v;
			},
			resultsClass: "autocomplete-select make-autocomplete",
			minChars: 0,
			max: 300,
			scroll: true,
			scrollHeight: 260,
			matchContains: true
		}).result(function(event,item,value) {
			//console.log(event,item.id);
			if (window._last_selected_brand_id && _last_selected_brand_id == item.id) return;
			$model.trigger("keypress");

			_last_selected_brand = item.v;
			_last_selected_brand_id = item.id;
			$model.val("")
				.unautocomplete()
				.autocomplete(_data_brand_phones[item.id],{
					/*formatItem: function(item) {
						return item.v;
					},*/
					resultsClass: "autocomplete-select model-autocomplete",
					minChars: 0,
					max: 300,
					scroll: true,
					scrollHeight: 250,
					matchContains: true
				})
				.result(function(event,item,value) {
					_last_selected_phone = item[1];
					model_search();
					clearTimeout(Truck.get("temp.model-autocomplete-timer"));
				});
			$model.unbind("keydown",model_keydown).keydown(model_keydown);
			$model.unbind("keypress",model_keypress).keypress(model_keypress);
			$model.unbind("focus",model_focus).focus(model_focus);
			setModelBlur();
		})
		.change(function(){
			if (this.value == "") {
				$model.unautocomplete().val("");
				setModelBlur();
				$model.blur();
				$("#findbox .image img").attr("src", "/img/select-phone-image.png");
			}
		});
		$make.nextAll("a.btn_dropdown").click(function(){
			$model.unautocomplete().val("");
			setModelBlur();
			$model.blur();
			$("#findbox .image img").attr("src", "/img/select-phone-image.png");
			$make.trigger("open");
		});
		$model.nextAll("a.btn_dropdown").click(function(){
			$model.trigger("keypress");
			$model.trigger("open");
		});

		$model.unbind("keydown",model_keydown).keydown(model_keydown);
		$model.unbind("keypress",model_keypress).keypress(model_keypress);
		$model.unbind("focus",model_focus).focus(model_focus);
		$("#findbox div.btn-redbut").click(function(){
			if ($model.val() == "") return false;
			var id = getModelIdFromName($model.val());
			if (id) window.location = "/process/step1/"+id+"/";
		});
		//$model.keydown(model_keydown);
		//$model.keypress(model_keypress);
	})(jQuery);
	var $makeEg = $make.prev(".eg"),
		$modelEg = $model.prev(".eg");
	$make.focus(function(){
		clearTimeout(Truck.get("timeout.makeEg"));
		$makeEg.hide();
	}).blur(function(){
		Truck.set("timeout.makeEg",setTimeout(function(){
			if ($make.val() == "") $makeEg.show(100);
		},300));
	});
	$makeEg.click(function(){
		$make.focus();
	});
	$model.focus(function(){
		clearTimeout(Truck.get("timeout.modelEg"));
		$modelEg.hide();
	});
	function setModelBlur() {
		$model.blur(function(){
			Truck.set("timeout.modelEg",setTimeout(function(){
				if ($model.val() == "") $modelEg.show(100);
			},300));
		});
	}
	setModelBlur();

	$modelEg.click(function(){
		$model.focus();
	});
	return;
	(function($) {
		$.widget("ui.combobox", {
			_create: function() {
				var self = this;
				var select = this.element.hide();
				var input = $("<input>")
					.insertAfter(select)
					.addClass("clear")
					.autocomplete({
						source: function(request, response) {
							var matcher = new RegExp(request.term, "i");
							response(select.children("option").map(function() {
								var text = $(this).text();
								if ((!request.term || matcher.test(text)) && text != "")
									return {
										id: $(this).val(),
										label: text.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + request.term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"),
										value: text
									};
							}));
						},
						delay: 0,
						select: function(e, ui) {
							if (window._model_autocomplete_input) window._model_autocomplete_input.attr("value","");
							if (!ui.item) {
								// remove invalid value, as it didn't match anything
								$(this).val("");
								return false;
							}
							$(this).focus();
							select.val(ui.item.id);
							self._trigger("selected", null, {
								item: select.find("[value='" + ui.item.id + "']")
							});
						},
						open: function() {
							//CSBfleXcroll('autocomplete-make');
						},
						minLength: 0
					})
					.addClass("ui-widget ui-widget-content ui-corner-left");
				input.autocomplete("widget").parent("div").attr("id","autocomplete-make");
				//CSBfleXcroll('autocomplete-make');
				/*$("<button>&nbsp;</button>")
				.insertAfter(input)
				.button({
					icons: {
						primary: "ui-icon-triangle-1-s"
					},
					text: false
				}).removeClass("ui-corner-all")
				.addClass("ui-corner-right ui-button-icon")
				.position({
					my: "left center",
					at: "right center",
					of: input,
					offset: "-1 0"
				}).css("top", "")
				.click(function() {
					// close if already visible
					if (input.autocomplete("widget").is(":visible")) {
						input.autocomplete("close");
						return;
					}
					// pass empty string as value to search for, displaying all results
					input.autocomplete("search", "");
					input.focus();
				});*/
			}
		});
		$.widget("ui.combobox_model", {
			_create: function() {
				var self = this;
				var select = this.element.hide();
				var input = $("<input>")
					.insertAfter(select)
					.addClass("clear")
					.autocomplete({
						source: function(request, response) {
							/*if (phones[$make.attr("value")]) {
								var html = '';
								$.each(phones[$make.attr("value")], function(id,model){
									html += '<option value="'+id+'">'+model+'</option>';
								});
								$model.html(html);
							} else $model.html("");*/

							var result = [];
							var matcher = new RegExp(request.term, "i");
							var count = 0;
							for (var id in phones[$make.attr("value")])
							{
								var model = phones[$make.attr("value")][id].model;
								var img = phones[$make.attr("value")][id].img;

								if ((!request.term || matcher.test(model)) && count < 10)
								{
									count++;
									result.push({
										id: id,
										label: model.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + request.term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"),
										value: model,
										image: img
									});
								}
							}
							response(result);
							/*var matcher = new RegExp(request.term, "i");
							response(select.children("option").map(function() {
								var text = $(this).text();
								if (!request.term || matcher.test(text))
									return {
										id: $(this).val(),
										label: text.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + request.term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"),
										value: text
									};
							}));*/
						},
						delay: 0,
						select: function(e, ui) {
							/*if (!ui.item) {
								// remove invalid value, as it didn't match anything
								$(this).val("");
								return false;
							}
							$(this).focus();
							select.val(ui.item.id);
							self._trigger("selected", null, {
								item: select.find("[value='" + ui.item.id + "']")
							});*/
							_last_selected_phone = ui.item.id;
							$("#findbox .image img").attr("src", "/img/nophoto.gif");
							var image = "/8mobile-handsets/mobile-phones/8-mobile-"+ui.item.u+"."+ui.item.image;
							$("<img>").load(function(){
								$("#findbox .image img").hide().attr("src", image).attr("alt",ui.item.value).fadeIn(800);
								$(this).remove();
							}).attr("src", image);
							//$("#findbox .image img").hide().attr("src", "/8mobile-handsets/mobile-phones/8-mobile-"+ui.item.id+"."+ui.item.image).attr("alt",ui.item.value).fadeIn(800);
						},
						minLength: 0
					})
					.addClass("ui-widget ui-widget-content ui-corner-left");
				_model_autocomplete_input = input;
				/*$("<button>&nbsp;</button>")
				.insertAfter(input)
				.button({
					icons: {
						primary: "ui-icon-triangle-1-s"
					},
					text: false
				}).removeClass("ui-corner-all")
				.addClass("ui-corner-right ui-button-icon")
				.position({
					my: "left center",
					at: "right center",
					of: input,
					offset: "-1 0"
				}).css("top", "")
				.click(function() {
					// close if already visible
					if (input.autocomplete("widget").is(":visible")) {
						input.autocomplete("close");
						return;
					}
					// pass empty string as value to search for, displaying all results
					input.autocomplete("search", "");
					input.focus();
				});*/
			}
		});

	})(jQuery);

	$(function() {
		$make.combobox();
		$model.combobox_model();
		$("#findbox div.btn-redbut").click(function(){
			/*if (!window._model_autocomplete_input) return false;
			if (window._model_autocomplete_input.attr("value") == "") return false;
			if (window._model_autocomplete_input.attr("value") == "") return false;
			if (!window._last_selected_phone) return false;*/

			if (!window._last_selected_phone || $model.val() == "") return false;
			window.location = "/process/step1/"+_last_selected_phone+"/";
		});
	});
}

$(function() {
_change_password = function() {
	var $content = $("#password-change").clone().appendTo("body").hide().width(270).attr("id", "password-change-clon");
	Flybox.show($content);
	_change_password_form($content);
}
_change_password_form = function($content) {
	var $contentContainer = $("<div/>").appendTo("body").hide().width(270).attr("id", "password-change-clon");
	$("form",$content).ajaxForm({
		target: $contentContainer,
		beforeSerialize: function() {
			Flybox.preloader.show();
		},
		success: function() {
			Flybox.show($contentContainer);
			_change_password_form($contentContainer);
			
		}
	});
}
_profile_form = function() {
	$("#register").ajaxForm({
		//target: $("#register").parent(),

		beforeSubmit: function(arr, $form, options) {
			$(".btn-redbut",$form).removeAttr("onclick").addClass("button_disable");
			disable($form.parent());
		},
		success: function(response, status, xhr, $form) {
			if (response.indexOf("form_error-box") == -1) {
				Truck.get("window").show('<div class="process-imeicheck win-success"><h2>Successful!</h2><p>Your account information has been updated.</p><div class="btn-multi btn-redbut" onclick="Truck.get(\'window\').hide();"><div><div>Ok</div></div></div></div>');
			}
			undisable($form.parent());
			$form.parent().html(response);
			_profile_form();
			$("body:not(:animated)").animate({scrollTop: $("#register").parent().offset().top}, 500 );
			$("html").animate({scrollTop: $("#register").parent().offset().top}, 500 );
		}
	});
}
_terms_popup = function() {
	var page = arguments.length ? arguments[0] : "terms-and-conditions";
	Flybox.ajax("/"+page+"/?print&ajax",{width: 600, height: 500});
}
_login_popup = function() {
	Flybox.preloader.show();
	var $content = $("<div/>").load("/my-8account/login/",function(){
		var child = $content.children();
		Flybox.show(child.appendTo("body").hide());
		_login_popup_form(child);
	});
}
_login_popup_form = function($content) {
	var $contentContainer = $("<div/>");
	$("form",$content).ajaxForm({
		target: $contentContainer,
		beforeSerialize: function() {
			Flybox.preloader.show();
		},
		success: function() {
			if ($contentContainer.text() == "login") {
				window.location = "/my-8account/profile/";
				return;
			}
			var child = $contentContainer.children();
			Flybox.show(child.appendTo("body").hide());
			_login_popup_form(child);
		}
	});
			}
_certificates_popup = function() {
	Flybox.rame('https://sealinfo.thawte.com/thawtesplash?form_file=fdf/thawtesplash.fdf&dn=WWW.8MOBILE.COM&lang=en', jQuery.browser.msie ? 520 : 516, 400);
}
_checkmend_popup = function() {
		//Truck.get('window').show('<div style="width:300px"><h2>About CheckMEND</h2><p>CheckMEND searches the world\'s largest database of stolen and counterfeit goods and disabled mobile phones, with over 40 billion serial numbered items of property with information that is potentially relevant to any purchaser. The information is updated in real time every few minutes by law enforcement, insurers, industry bodies and the public in over 40 countries.</p><p>For more information, please visit <a href="http://www.checkmend.com" target="blank">www.checkmend.com</a></p></div>');
		Flybox.show($('<div style="width:300px"><h2>About CheckMEND</h2><p>CheckMEND searches the world\'s largest database of stolen and counterfeit goods and disabled mobile phones, with over 40 billion serial numbered items of property with information that is potentially relevant to any purchaser. The information is updated in real time every few minutes by law enforcement, insurers, industry bodies and the public in over 40 countries.</p><p>For more information, please visit <a href="http://www.checkmend.com" target="blank">www.checkmend.com</a></p></div>').hide().appendTo($("body")));
}
Truck.set("window",{
	bg : $(".disablePage:first"),
	win : $("#phoneWindow"),
	content : $("#phoneWindow .content"),
	callback : {close: function(){},prev: function(){},next: function(){}},
	screen : {
		width: function(){
			return (window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth));
		},
		height: function(){
			return (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight));
		}
	},
	getTop : function()
	{
		var height = arguments.length ? arguments[0] : this.win.height();
		var top = parseInt((this.screen.height() - height) / 2);
		return (top < 0) ? 0 : top;
	},
	getLeft : function()
	{
		var width = arguments.length ? arguments[0] : this.win.width();
		var left = (this.screen.width() - width) / 2;
		return (left < 0) ? 0 : left;
	},
	fitCheck : function()
	{
		var $content = arguments.length ? arguments[0] : $(".content",this.win);
		if (this.win.height() > this.screen.height())
		{
			$(".content",this.win).css("overflow", "auto").height(this.screen.height()-28*2);
			if (this.win.width()+10 <= this.screen.width()) $(".content",this.win).width(($content.width() == 0 ? this.win.width() : $content.width())-56+20);
		}
		this.win.width();
		
	},
	show : function(content)
	{
		if (this.win.css("display") != "none") return this.move(content);

		this.hidePrev();
		this.hideNext();
		this.hideBack();

		if (typeof content == "object")
			return Flybox.show(content);

		var $content = $(".content",this.win);
		$content.removeAttr("style").html(content);

		this.win.removeAttr("style").css("left",this.getLeft()+"px").css("top",this.getTop()+"px");

		this.fitCheck();
		//this.win.width(this.win.width()).height(this.win.height());
		//$content.parent(".bg").width(this.win.width()-28*2).height(this.win.height()-28*2);

		//$content.hide();
		this.win.stop(true);
		
		var self = this;
		this.bg.fadeIn(300,function(){
			self.win.fadeIn(800,function(){
				//$content.show();
				//Truck.get("window").move(c);
			});
		});
	},
	showPre : function(content)
	{
		if (this.win.css("display") != "none") return this.move(content);

		this.hidePrev();
		this.hideNext();

		$(".content",this.win).removeAttr("style").html("<div>asd fd dfg dfg df fd gfdg f f</div>");

		//this.win.css("left",this.getLeft()+"px").css("top",this.getTop()+"px");
		var t = this;
		//this.win.stop(true);
		this.bg.fadeIn(300,function(){
			t.win.stop().fadeIn(800,function(){
				//$(".content",t.win).removeAttr("style");
				t.move("<div>asdasfasdf</div>");//content
				/*var $content = $(content).appendTo("body");
				var width = $content.width();
				var height = $content.height();
				var left = t.getLeft(width+56);
				var top = t.getTop(height+58);
				t.win.stop(true);
				t.win.find(".content").stop(true);
				t.win.find(".content").removeAttr("style").animate({width: width, height: height}, 1000);
				t.win.animate({left: left, top: top}, 1000, function(){
					t.win.find(".content").html($content.fadeIn());
				});*/
			});
		});
	},
	move : function(content)
	{
		if (typeof content == "object")
			return Flybox.show(content);

		var $content = $(content).appendTo("body");
		return Flybox.show($content);
		//this.fitCheck($content);

		var width = $content.width();
		var height = $content.height()+28*2 <= this.screen.height() ? $content.height() : this.screen.height()-28*2;

		//this.content.removeAttr("style");
		this.content.css("overflow","hidden");
		if ($content.height()+28*2 >= this.screen.height()) {
			this.content.css("overflow","auto");
			width += 20;
		}

		var left = this.getLeft(width+56);
		var top = this.getTop(height+58);

		if (   parseInt(this.win.find(".content").width()) != width
			|| parseInt(this.win.find(".content").height()) != height
			|| parseInt(this.win.css("left")) != left
			|| parseInt(this.win.css("top")) != top
		) {
			this.win.stop(true);
			//this.win.find(".content").stop(true);
			//$("#phoneWindow .content").stop().animate({width: "300px", height: "200px"}, 1000, function(){$content.fadeIn()});
			this.content.stop(true).animate({width: width, height: height}, 1000).html($content.fadeIn());
			this.win.animate({left: left, top: top}, 1000);
		} else {
			this.content.html($content.fadeIn());
		}
	},
	show2 : function(content)
	{
		var self = this;
		//TODO: если контент не обёрнут ни каким боксом - сделать это
		var $content = $(content).appendTo($("<div>").hide().appendTo("body"));

		this.win.removeAttr("style");
		this.content.removeAttr("style");

		if (this.win.css("display") == "none")
		{
			this.hideClose();
			this.hidePrev();
			this.hideNext();
			
			this.content.empty().width(50).height(50);
			this.win.css("left",this.getLeft()+"px").css("top",this.getTop()+"px");
			this.bg.fadeIn(300,function(){
				self.win.fadeIn(800,function(){
					//$content.show();
					//Truck.get("window").move(c);
				});
			});
			$.idle(1100);
		}
		this.move(content);
		

		//this.win.css("left",this.getLeft()+"px").css("top",this.getTop()+"px");
	},
	hide : function()
	{
		this.win.stop(true);
		var t = this;
		this.win.fadeOut(300,function(){
			t.bg.fadeOut(300);
		});
	},
	showPrev : function() {this.win.find("a.prev_btn").show();},
	hidePrev : function() {this.win.find("a.prev_btn").hide();},
	showNext : function() {this.win.find("a.next_btn").show();},
	hideNext : function() {this.win.find("a.next_btn").hide();},
	showBack : function() {this.win.find("a.back_btn").show();},
	hideBack : function() {this.win.find("a.back_btn").hide();},
	showClose : function() {this.win.find("a.close_btn").show();},
	hideClose : function() {this.win.find("a.close_btn").hide();},

	setPrev : function(start, callback)
	{
		this._prev = start;
		this.callback.prev = callback;
		/*
		 * хак для Flybox
		 */
		this.win = $("#flybox");
		this.win.append('<a class="prev_btn"></a>');

		this.win.find("a.prev_btn").unbind().click(function(){
			var win = Truck.get("window");
			win._next = win._current;
			win._current = win._prev;
			win._prev = win.callback.prev(win._prev);
			return false;
		});
	},
	setNext : function(start, callback)
	{
		this._next = start;
		this.callback.next = callback;
		/*
		 * хак для Flybox
		 */
		this.win = $("#flybox");
		this.win.append('<a class="next_btn"></a>');

		this.win.find("a.next_btn").show().unbind().click(function(){
			var win = Truck.get("window");
			win._prev = win._current;
			win._current = win._next;
			win._next = win.callback.next(win._next);
			return false;
		});
	},
	setBack : function(callback)
	{
		/*
		 * хак для Flybox
		 */
		this.win = $("#flybox");
		this.win.append('<a class="back_btn"></a>');

		this.win.find("a.back_btn").show().unbind().click(callback);
	},
	_prev : 0,
	_next : 0,
	_current : 1
});
Truck.set("handler_click_brand",function(){
		if ($(this).attr("id"))
			_bid = $(this).attr("id");
		else {
			var regex = /([0-9]+)\/$/;
			_bid = parseInt(regex.exec($(this).attr("href")));
		}
		_bid_count = 0;
		for (var id in phones[_bid]) _bid_count++;

		var html = _phone_selector_paging(_bid,1);
		var win = Truck.get('window');
		win.show({id:$(html).appendTo("body").hide(), managePanelTop:true, managePanelBottom:true});
		if (_bid_count > 10) {
			win.setPrev(0,function(n){
				win.hidePrev();
				if (n > 1) win.showPrev();
				if (n < _bid_count/10) win.showNext();

				win.move(_phone_selector_paging(_bid,n));
				return n-1;
			});
			win.setNext(2,function(n){
				win.hideNext();
				if (n < _bid_count/10) win.showNext();
				if (n > 1) win.showPrev();

				win.move(_phone_selector_paging(_bid,n));
				return n+1;
			});
		}
		win.setBack(function(){
			win.hideBack();
			_phone_selector();
			return false;
		});

		return false;
	});
_phone_selector = function() {

	var $content = $("#brands-box").clone().show();
	//var $content = $("#brands-box").show();
	$content.width(300);
	$("a",$content).unbind().click(Truck.get('handler_click_brand'));
	var win = Truck.get('window');
	
	win.hidePrev();
	win.hideNext();
	win._prev = win._next = 0;
	win._current = 1;

	$content.appendTo("body");
	win.show($content);
}
_phone_selector_paging = function(brand,page_number) {
	var per_page = 10;
	var count = -1;
	var html = '<div class="popup-phones phone-search"><h2>Choose by model</h2>';
	$.each(phones[brand],function(i,phone){
		count++;
		if (count > per_page*page_number) return false;
		if (!(count < per_page*page_number && count >= per_page*page_number-per_page)) return true;

		for(var ii in _data_brands) {
			if (!_data_brands.hasOwnProperty(ii)) continue;
			if (_data_brands[ii].id == brand) var brand_name = _data_brands[ii].v;
		}

		html += '<a href="/sell-recycle/mobile-phone/'+phone.u+'/"><span class="image"><img src="/8mobile-handsets/mobile-phones/8-mobile-'+phone.u+'.'+phone.img+'" alt="'+brand_name+' '+phone.model+' – 8 mobile"></span><span class="model">'+phone.model+'</span><span class="model for">For:</span><span class="price">&pound;'+phone.p+'</span><span class="sell">Sell mobile!</span></a>';
	});
	html += '</div>';
	return html;
}
if ($("#brandOnHome").length) $("#brandOnHome a").click(Truck.get('handler_click_brand'));
});


/* functions */
function number_format( number, decimals, dec_point, thousands_sep ) {
    var i, j, kw, kd, km;
    // input sanitation & defaults
    if( isNaN(decimals = Math.abs(decimals)) ){
        decimals = 2;
    }
    if( dec_point == undefined ){
        dec_point = ".";
    }
    if( thousands_sep == undefined ){
        thousands_sep = ",";
    }
    i = parseInt(number = (+number || 0).toFixed(decimals)) + "";

    if( (j = i.length) > 3 ){
        j = j % 3;
    } else{
        j = 0;
    }
    km = (j ? i.substr(0, j) + thousands_sep : "");
    kw = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep);
    //kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).slice(2) : "");
    kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).replace(/-/, 0).slice(2) : "");
    return km + kw + kd;
}

$(function() {
tooltip=function(){
	var id = 'tt';
	var top = 3;
	var left = 15;
	var maxw = 300;
	var speed = 10;
	var timer = 20;
	var endalpha = 90;
	var alpha = 0;
	var tt,t,c,b,h;
	var ie = document.all ? true : false;
	return{
		show:function(v,w){
			if(tt == null){
				tt = document.createElement('div');
				tt.setAttribute('id',id);
				t = document.createElement('div');
				t.setAttribute('id',id + 'top');
				c = document.createElement('div');
				c.setAttribute('id',id + 'cont');
				b = document.createElement('div');
				b.setAttribute('id',id + 'bot');
				tt.appendChild(t);
				tt.appendChild(c);
				tt.appendChild(b);
				document.body.appendChild(tt);
				tt.style.opacity = 0;
				tt.style.filter = 'alpha(opacity=0)';
				document.onmousemove = this.pos;
			}
			tt.style.display = 'block';
			c.innerHTML = v;
			tt.style.width = w ? w + 'px' : 'auto';
			if(!w && ie){
				t.style.display = 'none';
				b.style.display = 'none';
				tt.style.width = tt.offsetWidth;
				t.style.display = 'block';
				b.style.display = 'block';
			}
			if(tt.offsetWidth > maxw){tt.style.width = maxw + 'px'}
			h = parseInt(tt.offsetHeight) + top;
			clearInterval(tt.timer);
			tt.timer = setInterval(function(){tooltip.fade(1)},timer);
		},
		pos:function(e){
			var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
			var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;
			tt.style.top = (u) + 'px';
			tt.style.left = (l + left) + 'px';
		},
		fade:function(d){
			var a = alpha;
			if((a != endalpha && d == 1) || (a != 0 && d == -1)){
				var i = speed;
				if(endalpha - a < speed && d == 1){
					i = endalpha - a;
				}else if(alpha < speed && d == -1){
					i = a;
				}
				alpha = a + (i * d);
				tt.style.opacity = alpha * .01;
				tt.style.filter = 'alpha(opacity=' + alpha + ')';
			}else{
				clearInterval(tt.timer);
				if(d == -1){tt.style.display = 'none'}
			}
		},
		hide:function(){
			clearInterval(tt.timer);
			tt.timer = setInterval(function(){tooltip.fade(-1)},timer);
		}
	};
}();
});
