function number_format(number, decimals, dec_point, thousands_sep) {
	// ORIGINALLY FROM https://github.com/kvz/phpjs/raw/master/functions/strings/number_format.js
    number = (number+'').replace(',', '').replace(' ', '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

// enable nginx cache for basket module
$(function() {
	$.getJSON('./?a=ping', function(data) {
		// and when you're dead I will be still alive.
	});
});

// coverage map section
$(function() {
	function switchtab(obj) {
		$('div.cov-map ul.switcher li').removeClass('act');
		obj.addClass('act');
		var img_id = "coverage_map_" + obj.attr('id').substr(13);
		$('div.cov-map div.pic img').hide();
		$('div.cov-map div.pic img#'+img_id).show();

		var aObj = $('div.cov-map div.pic img#'+img_id).parents('a');
		aObj.attr('href', $('div.cov-map div.pic img#'+img_id).attr('rel'));
		aObj.attr('target', '_blank');
	}

	$('div.cov-map ul.switcher li').each(function() {
		$(this).click(function() {
			switchtab($(this));
		});
	});

	$('div.cov-map ul.switcher li').first().each(function(){
		switchtab($(this));
	});
});

// region selector
$(function() {
	$('div.region form select#region').change(function() {
		$(this).parents('form').submit();
	});
});

// news section
$(function() {
	$('ul.calendar li.cur div.month').click(function() {
		var li = $(this).parents('li');
		if($(this).hasClass('open')) {
			$(this).removeClass('open');
			li.find('div.months').hide();
		} else {
			$(this).addClass('open');
			li.find('div.months').show();
		}
	});
});

// services html menu
$(function() {
	var servicesMenuPath = $('ul#services-btns').attr('pp:menupath');

	if(servicesMenuPath != undefined && servicesMenuPath.length > 0) {
		$.getJSON(servicesMenuPath, function(data) {
			var _keys = [];
			for(key in data) {
				if(parseInt(key) > 0) {
					_keys.push(key);
				}
			}
			_keys.sort();
			for(x=0; x < _keys.length; x++) {
				var key = _keys[x];
				var link = $('<a></a>');
				link.attr('href', data[key].link);
				link.attr('title', data[key].title);
				link.text(data[key].title);

				var li = $('<li></li>');
				li.addClass(data[key].liclass);
				li.append(link);
				$('ul#services-btns').append(li);
			}
		});
	}
});

// service menu
$(function(){
	function switchSection(item_id) {
		$('li.struct').each(function(index){ $(this).removeClass('cur'); });
		$('ul.service').each(function(index){ $(this).css('display', 'none'); });
		$('li.service').each(function(index){ $(this).removeClass('cur'); });

		$('li.struct#struct_'+item_id).addClass('cur');
		$('ul.service#substruct_'+item_id).css('display', 'block');
	}

	function switchBaloon(item_id, show) {
		$('li.service').each(function(index){ $(this).removeClass('cur'); });
		$('dl.baloon').each(function(index){ $(this).css('display', 'none'); });

		if(show) {
			$('li.service#service_'+item_id).addClass('cur');
			$('div#baloonwrap').css('display', 'block');
			$('dl.baloon#baloon_'+item_id).css('display', 'block');

		} else {
			$('div#baloonwrap').css('display', 'none');
		}
	}

	$('li.struct').each(function(index){
		$(this).click(function(){
			switchSection($(this).attr('item_id'));
			switchBaloon(-1, false);
			return false;
		});
	});

	$('li.service').each(function(index){
		$(this).click(function(){
			switchBaloon($(this).attr('item_id'), true);
			return false;
		});
	});
});

// tarrifs
$(function() {
	$('.tariff-services .title a').click(function(event) {
		$(this).parent().parent().toggleClass('open');
	});
});

// career
$(function() {
	$('dl.vacancy>dt a').click(function() {
		if($(this).parents('dl').hasClass('open')) {
			$(this).parents('dl').removeClass('open');
		} else {
			$(this).parents('dl').addClass('open');
		}

		return false;
	});
});

// how to buy
$(function() {
	function disableDropDown(type) {
		$('#'+type).empty();
		$('#'+type).attr('disabled', 'disabled');
	}

	function enableDropDown(type, id) {
		$.getJSON('/howbuy.json?type='+type+'&id='+id, function(data) {
			var first = 1;

			for (k in data) {
				if (first) {
					first = 0;
					$('#'+type).removeAttr('disabled');
				}

				var option = $('<option></option>');
				option.attr('value', data[k].id);
				option.append(data[k].title);

				$('#'+type).append(option);
			}
		});
	}

	$('#city').change(function(event) {
		disableDropDown('metro');
		enableDropDown('metro', $(this).val());
	});

});

// device
$(function() {
	$('div.spec-wrap').each(function() {
		var div = this;
		$('div.full', div).css('display', 'none');
		$('h3 span.full', div).css('display', 'inline');
		$('h3 span.short', div).css('display', 'none');

		$('h3 span.full a', div).click(function() {
			$('div.short', div).css('display', 'none');
			$('div.full', div).css('display', 'block');
			$('h3 span.short', div).css('display', 'inline');
			$('h3 span.full', div).css('display', 'none');

			return false;
		});

		$('h3 span.short a', div).click(function() {
			$('div.short', div).css('display', 'block');
			$('div.full', div).css('display', 'none');
			$('h3 span.short', div).css('display', 'none');
			$('h3 span.full', div).css('display', 'inline');

			return false;
		});
	})
});

// banners
$(function() {
	$('.adplace').each(function() {
		var place = this.getAttribute('pp:adplace');
		var rid = this.getAttribute('pp:rid');
		var filterLine = this.getAttribute('pp:filterline');
		var isSimple = this.getAttribute('pp:simple');
		var tpl = this.getAttribute('pp:tpl');

		var placeholder = this;
		$.getJSON('/show/?p='+place+'&fl='+filterLine+'&fv='+rid+'&t='+tpl, function(banner) {
			if (isSimple == 'undefined') {
				placeholder.innerHTML = '<li class="promo"><a href="/clk/?p='+place+'&b='+banner.id+'"><img src="'+banner.image+'"alt=""/></a></li>';
			} else {
				placeholder.innerHTML = '<a href="/clk/?p='+place+'&b='+banner.id+'"><img src="'+banner.image+'"alt=""/></a>';
			}
		});
	});
});

// device
$(function() {
	function switchPhoto(id) {
		$('span#gallery img').hide().each(function() {
			var current_id = $(this).attr('id').substr(11);
			if(id == current_id) {
				$('ul.previews').attr('gallery:current', id);
				$(this).show();
			}
		});
	}

	var current_id = parseInt($('ul.previews:first').attr('gallery:current'));
	var max_id = parseInt($('ul.previews:first').attr('gallery:count'));

	$('ul.previews').each(function() {
		var ul = $(this);
		var current_id = parseInt(ul.attr('gallery:current'));
		var max_id = parseInt(ul.attr('gallery:count'));

		$('li.gallery-photo a', ul).bind('click', function(event) {
			var id = $(this).attr('id').substr(13);
			switchPhoto(id);
			event.preventDefault();
			return false;
		});
	});

	$('ul.previews li.prev a').bind('click', function(event) {
		if(current_id > 1) {
			current_id -= 1;
			switchPhoto(current_id);
		}
		event.preventDefault();
		return false;
	});

	$('ul.previews li.next a').bind('click', function(event) {
		if(current_id < max_id) {
			current_id += 1;
			switchPhoto(current_id);
		}
		event.preventDefault();
		return false;
	});

});

// esdevice
$(function() {
	function switchPhoto(id) {
		$('div.device-card div.pic img').hide().each(function() {
			var current_id = $(this).attr('id').substr(11);
			if(id == current_id) {
				$('ul.previews').attr('gallery:current', id);
				$(this).show();
			}
		});
	}

	var current_id = parseInt($('ul.previews:first').attr('gallery:current'));
	var max_id = parseInt($('ul.previews:first').attr('gallery:count'));

	$('span#esgallery ul.previews').each(function() {
		var ul = $(this);
		var current_id = parseInt(ul.attr('gallery:current'));
		var max_id = parseInt(ul.attr('gallery:count'));

		$('li.gallery-photo a', ul).bind('click', function(event) {
			var id = $(this).attr('id').substr(13);
			switchPhoto(id);
			event.preventDefault();
			return false;
		});
	});

	$('span#esgallery ul.espreviews li.prev a').bind('click', function(event) {
		if(current_id > 1) {
			current_id -= 1;
			switchPhoto(current_id);
		}
		event.preventDefault();
		return false;
	});

	$('span#esgallery ul.espreviews li.next a').bind('click', function(event) {
		if(current_id < max_id) {
			current_id += 1;
			switchPhoto(current_id);
		}
		event.preventDefault();
		return false;
	});
});


//print links
$(function() {
	$('a.print').click(function() {
		window.print();
		return false;
	})
});

// mediakit photos
$(function() {
	var showgallery = function() {
		$(this).parents('li').children('div.gallery-photos').trigger('click');
		return false;
	}
	$('ul.gallery-stndr li div.pic a').click(showgallery);
	$('ul.gallery-stndr li h5 a').click(showgallery);
});


// message length
$(function() {
	$('form.send-sms textarea#message').keyup(function(){
		var value = $(this).val();
		var limit = 126; // you shall not pass this value, this checked on server-side.
		if(value.length > limit) {
			value = value.substr(0, limit);
			$(this).val(value);
		}
		$('p.notice span.count').html(value.length);
	});
});

$(function() {
	function isiPhone(){
		return (
			(navigator.platform.indexOf("iPhone") != -1) ||
			(navigator.platform.indexOf("iPod") != -1) ||
			(navigator.platform.indexOf("iPad") != -1)
		);
	}
	if(isiPhone()) {
		var objList = $('div.nav ul li a').each(function() {
			$(this).hover(function(e) {
				var target = $(this).attr('target');
				if(target == '') {
					window.location = $(this).attr('href');
					e.stopPropagation();
					e.preventDefault();
				}
				return e;
			});
		});
	}
});

// basket code
$(function() {
	$('div.basket div.b-heading').bind('click', function() {
		if($('div#basket-body').hasClass('hidden') == true) {
			$('div#basket-body').removeClass('hidden');
		} else {
			$('div#basket-body').addClass('hidden');
		}
	});
	$('div#basket-body ul.actions li.hide').bind('click', function() {
		if($('div#basket-body').hasClass('hidden') == false) {
			$('div#basket-body').addClass('hidden');
		}
	});
});

// step1 code
$(function() {
	function updatePrice(option) {
		// update table row
		var object_price = parseInt(option.parents('tr:first').find('p.price').attr('pp:original'));
		if(option.parents('div:first').find('input.tariff-enabled').is(':checked')) {
			var total = (object_price + parseInt(option.attr('pp:price')));
			var totalStr = number_format(total, 0, '.', ' ');
			option.parents('tr:first').find('p.price').find('strong').html(totalStr);
		} else {
			var totalStr = number_format(object_price, 0, '.', ' ');
			option.parents('tr:first').find('p.price').find('strong').html(totalStr);
		}

		// update total price
		var totalPrice = 0;
		$('table.basket tbody tr').each(function() {
			if($(this).find('input.tariff-enabled').is(':checked')) {
				totalPrice += parseInt($(this).find('select#select').find(':selected').attr('pp:price'));
			}
			totalPrice += parseInt($(this).find('p.price').attr('pp:original'));
		});
		$('div.total strong').html(number_format(totalPrice, 0, '.', ' '));
	}

	$('div.extra-box input.tariff-enabled').bind('click', function() {
		$(this).parents('div:first').find('select#select').find(':selected').each(function() {
			updatePrice($(this));
		});
	});

	$('div.extra-box fieldset.chk label').bind('click', function() {
		$(this).parents('div.extra-box:first').find('select#select').find(':selected').each(function() {
			updatePrice($(this));
		});
	});

	$('div.extra-box select#select').bind('change', function() {
		$(this).find(':selected').each(function() {
			updatePrice($(this));
		});
	});

	$('div.next-step a').bind('click', function() {
		$('form#step1').submit();
		return false;
	});

	// updates for script generated code (like back to step1)
	$('div.extra-box select#select').find(':selected').each(function() {
			updatePrice($(this));
	});
});

// step2 code
$(function() {
	// validators object
	var validates = {
		full_name: function(e) {
			return (e.val().length > 5);
		},

		email: function(e) {
			emailre = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
			return (emailre.test(e.val()));
		},

		phone: function(e) {
			return (e.val().length > 5);
		},

		city: function(e) {
			return (e.val().length > 3);
		},

		street: function(e) {
			return (e.val().length > 5);
		},

		house: function(e) {
			return (e.val().length > 0);
		}
	};

	$('form#esstep2 fieldset.submit input').bind('click', function(event) {
		var ret = true;
		$('form#esstep2 input,form#esstep2 textarea').each(function() {
			var vfunc = $(this).attr('name');
			if(vfunc != '' && validates[vfunc] != undefined) {
				ret = ret && validates[vfunc]($(this));
				if(!ret) {
					var notice = $(this).attr('v:notice');
					if(notice != undefined) {
						alert(notice);
					}
					$(this).focus();
					event.preventDefault();
					return false;
				}
			}
		});
		return ret;
	});
});

$(function() {
	$('body.anketa input[type="radio"]').change(function() {
		if ($(this).attr("id") == 'moscow-region') {
			$('body.anketa .detail').show();
		} else {
			$('body.anketa input[name="district"]').attr('value', '');
			$('body.anketa input[name="locality"]').attr('value', '');
			$('body.anketa .detail').hide();

		}
	});
});

function setEqualHeight(columns)
{
	var tallestcolumn = 0;
	columns.each(
		function()
		{
			currentHeight = $(this).height();
			if(currentHeight > tallestcolumn)
			{
				tallestcolumn = currentHeight;
			}
		}
	);

	columns.height(tallestcolumn);
}

function setEqualHeightDevice(columns)
{
	var tallestcolumn = 0;
	columns.each(
		function()
		{
			var elem = $(this).find(".bordered-5");

			tallestcolumn = 0;
			elem.each(
				function()
				{
					currentHeight = $(this).height();
					if(currentHeight > tallestcolumn)
					{
						tallestcolumn = currentHeight;
					}
				}
			)
			elem.height(tallestcolumn);
			tallestcolumn = 0;
		}
	);


}

$(document).ready(function() {
	setEqualHeightDevice($("body.shop .devices"));
	setEqualHeight($("body.device .device-list li"));
});

