L = function(){}

if (!self.console) {
	console = {log: L}
}

var ColumnScroller = function(){
	this.init.apply(this, arguments)
}

ColumnScroller.prototype = {
	init: function(element){
		var t = this;
		t.$container = $(element)
		t.$viewport = $(".viewport", t.$container)
		t.$item_container = $(".item-container", t.$container)
		t.$items = $(".item", t.$container)
		t.$prev_control = $(".controls .prev", t.$container)
		t.$next_control = $(".controls .next", t.$container)
		t.animating = false
		t.target_coord = 0
		
		t.$prev_control.click(function(){
			t.prev()
		})

		t.$next_control.click(function(){
			t.next()
		})

		// если виден
		if (t.$container.attr("offsetHeight")) {
			t.move(0)
		} else {
			t.$container.one("showcontent", function(){
				t.move(0)
			})
		}
	},
	
	next: function(){
		this.move(+1)
	},
	
	prev: function(){
		this.move(-1)
	},
	
	move: function(x) {
		var t = this

		if (t.animating) {
			t.$item_container.stop()
		} else {
			t.target_coord = 0
		}

		
		
		var container_width = t.$item_container.attr("offsetWidth")
		var viewport_width = t.$viewport.attr("clientWidth")
		var min_left = viewport_width - container_width
		var cpos = t.target_coord || t.$item_container.attr("offsetLeft")
		var new_coord = cpos - viewport_width * x
		
		if (new_coord <= min_left) {
			new_coord = min_left
			t.$next_control.hide()
		} else {
			if (!t.$next_control.attr("offsetWidth")) {
				t.$next_control.show()
			}
		}
		
		if (new_coord >= 0) {
			new_coord = 0
			t.$prev_control.hide()
		} else {
			if (!t.$prev_control.attr("offsetWidth")) {
				t.$prev_control.show()
			}
		}
		
		t.target_coord = new_coord // куда едем
		t.animating = true
		t.$item_container.animate({left: new_coord}, 400, function(){t.animating = false})
	}
}

var TabController = function(){
	var t = this
	t.prefix = "tab-"
	
	$(".tabs > dt").click(function(){
		t.setActiveTab(this)
		return false
	})
}

TabController.prototype = {
	/**
	 * Синхронизация табов и location
	 */
	sync: function() {
		var location = window.location.toString()
		var anchor_data = ""
		var anchor_start = location.indexOf("#") 
		if (anchor_start != -1) {
			anchor_data = location.substring(anchor_start + 1).split(",")
			var anchor, id
			for (var i = 0, l = anchor_data.length; i < l; ++i) {
				anchor = anchor_data[i]
				if (anchor.indexOf(this.prefix) == 0) {
					var tab = document.getElementById(anchor.substring(this.prefix.length))
					if (tab) {
						this.setActiveTab(tab)
					}
				}
			}
		} else {
			
		}
	},
	
	setActiveTab: function(tab) {
		if (!tab) {return;}
		var tab = $(tab)
		tab.siblings().removeClass("selected").end().next().andSelf().addClass("selected")
		if ($.browser.msie && $.browser.version < 8) {
			tab.blur()
		}

		// при переключении таба вызываем onshowcontent для всех скроллеров
		tab.next().find(".column-scroller").trigger("showcontent")
		return false
	}
}

$(function(){
	$(".column-scroller").each(function(){
		new ColumnScroller(this)
	})
	
	window.tabs = new TabController()
	window.tabs.sync()
})

/* Генерация CSS для флагов стран */

var CSSFlagGenerator = function(){
	var start = "a".charCodeAt(0)
	var stop = "z".charCodeAt(0)
	var width = 16
	var height = 11
	var offsetLeft = - width
	var offsetTop = - height

	var r = "/* ISO 3166-1 */\n"


	var _generate = function(prefix){
		var prefix = prefix || ".flag-"
		for (var i = start; i <= stop; i++) {
			for (var j = start; j <= stop; j++) {
				r += prefix + String.fromCharCode(i) + String.fromCharCode(j) + "\t{background-position:" + ((start-i) * width + offsetLeft) + "px " + ((start-j) * height + offsetTop) + "px;}\n"
			}	
		}
		return r
	}
	
	return {
		generate: _generate
	}
}()

window.konami_code=[38,38,40,40,37,39,37,39,66,65];
window.konami_code.test_kc = function(x){for(var i=0,l=this.length;i<l;++i)if(x[i]!=this[i])return false;return true;}
window.onkonamicode = function(){}
window.input_buffer = new Array(window.konami_code.length);
$(document).bind('keyup.konami_listener',function(evt){with(window.input_buffer){shift();push(evt.which);}if(window.konami_code.test_kc(window.input_buffer)){$(this).unbind('keyup.konami_listener');window.onkonamicode();}}); 


window.onkonamicode = function(){
	var international_design = function(){
		var getRandomCountryCode = function(){
			var start = "a".charCodeAt(0)
			var stop = "z".charCodeAt(0)
			var length = stop-start
			var c1 = start + Math.floor(Math.random() * length)
			var c2 = start + Math.floor(Math.random() * length)
			return String.fromCharCode(c1) + String.fromCharCode(c2) 
		}
		
		var flags = $(".f")
		
		return function(){
			$(".designers .toc").html('<a href="#">F</a><a href="#">A</a><a href="#">S</a><a href="#">H</a><a href="#">I</a><a href="#">O</a><a href="#">N</a><a href="#"> </a><a href="#">I</a><a href="#">S</a><a href="#"> </a><a href="#">T</a><a href="#">H</a><a href="#">E</a><a href="#"> </a><a href="#">U</a><a href="#">N</a><a href="#">I</a><a href="#">V</a><a href="#">E</a><a href="#">R</a><a href="#">S</a><a href="#">E</a>')
			var className = ""
			for (var i = 0, flag; flag = flags[i]; ++i) {
				flag.className = "f flag-" + getRandomCountryCode()
			}
		}
	}()
	var i = setInterval(international_design, 125)
	setInterval(function(){
		clearInterval(i)
		location.reload()
	}, 15000)
}


/**
 * Table of contents
 * @see TOP.prototype.init
 */
var TOC = function(container){
	this.init.apply(this, arguments)
}

TOC.prototype = {
	/**
	 * @param {Element} container
	 */
	init: function(container, mode){
		var t = this
		t.mode = mode || 1 
		
		var line1_alphabet = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z".split(",")
		var line2_alphabet = "А,Б,В,Г,Д,Е,Ж,З,И,К,Л,М,Н,О,П,Р,С,Т,У,Ф,Х,Ц,Ч,Ш,Щ,Э,Ю,Я".split(",")
		var markers_aplhabet = []
		t.$container = $(container)
		t.$markers = $(".marker", t.$container)
		t.$item_container = $(".item-container", t.$container)
		t.$viewport = $(".viewport", t.$container)
		t.$next = $(".controls .next", t.$container)
		t.$prev = $(".controls .prev", t.$container)
		t.line = 1
		var toc = document.createElement("div")
		toc.className = "toc"
		var toc_html = ""
		if (t.mode == 1) {
			for (var i = 0, marker; marker = t.$markers[i]; ++i){
				markers_aplhabet[i] = marker.innerHTML.charAt(0).toUpperCase()
			}
			
			for (var i = 0, c; c = line1_alphabet[i]; ++i) {
				var letter_found = false
				for (var j = 0, marker; marker = markers_aplhabet[j]; ++j){
					if (c === marker) {
						letter_found = true
						break
					}
				}
				
				if (letter_found) {
					toc_html += "<a class=\"active\" href=\"#\" rel=\"" + j + "\">" + c + "</a>"
				} else {
					toc_html += "<a href=\"#\">" + c + "</a>"
				}
			}
			toc_html += "<br/>"
			for (var i = 0, c; c = line2_alphabet[i]; ++i) {
				var letter_found = false
				for (var j = 0, marker; marker = markers_aplhabet[j]; ++j){
					if (c === marker) {
						letter_found = true
						break
					}
				}
				
				if (letter_found) {
					toc_html += "<a class=\"active\" href=\"#\" rel=\"" + j + "\">" + c + "</a>"
				} else {
					toc_html += "<a href=\"#\">" + c + "</a>"
				}
			}
		} else if (t.mode == 2) {
			for (var i = 0, marker; marker = t.$markers[i]; ++i) {
				var html = marker.innerHTML
				/*
				if (!/^[a-z]/i.test(html) && t.line == 1){
					prefix = "<br/>"
					t.line = 2
				} else {
					prefix = ""
				}
				*/
				prefix = ""
				toc_html += prefix + "<a href=\"#\" class=\"active\" rel=\"" + i + "\">" + html + "</a>"
			}			
		}
		
		toc.innerHTML = toc_html
		t.$toc = $(toc)
		t.$toc.appendTo(t.$container)
		t.$toc.click(function(event){
			/**@type Element*/
			var target = event.target
			var marker = target.getAttribute("rel")
			if (marker !== null) {
				t.scrollToMarker(marker)
			}
			return false
		})
	},
	
	scrollToMarker: function(index) {
		var t = this
		if (typeof index === "undefined") return;
		
		if (index >= t.$markers.length) {
			index = t.$markers.length - 1
		}
		
		var marker = $(t.$markers[index])
		/** @type jQuery */
		var col = marker.parents(".col")
		var prev = col.prev()
		var new_position = 0
		
		while (prev.length) {
			new_position -= prev.attr("offsetWidth")
			prev = prev.prev()
		}
		
		var min_position = t.$viewport.attr("offsetWidth") - t.$item_container.attr("offsetWidth")
		
		if (new_position <= min_position) {
			new_position = min_position
			t.$next.hide()
		} else {
			t.$next.show()
		}
		
		if (new_position >= 0) {
			new_position = 0
			t.$prev.hide()
		} else {
			t.$prev.show()
		}
		
		t.$item_container.animate({left: new_position}, 200)
	}
}

/**
 * @param {Element} element Форма для валидации
 */

var FormValidator = function(element){
	this.init.apply(this, arguments)
}

FormValidator.prototype = {
	/**
	 * @alias FormValidator
	 */
	init: function(element){
		var t = this
		t.form = $(element)
		t.fields = $("input", element)
		t.submit = $(".submit", element)
		t.is_valid = t.validateAll()
		t.form.submit(function(){
			return t.is_valid
		})
		t.fields.change(function(){
			t.validateAll()
		})
		t.fields.keyup(function(){
			t.validateAll()
		})
	},
	
	validateAll: function(){
		var t = this;
		// презумпция невиновности пользователя
		var is_valid = true;
		var methodRe = new RegExp("validate-as-(\\S*)", "i");
		for (var i = 0; field = t.fields[i]; ++i) {
			var is_field_valid = true;
			var method = methodRe.exec(field.className)

			//если нет класса валидатора для поля, или такой валидатор не найден - считаем поле валидным
			if (method && method.length > 1) {
				method = method[1];
				var local_validator = t["validate-as-" + method];
				if (local_validator) {
					is_field_valid = local_validator(field.value);
					if (is_field_valid) {
						$(field).removeClass("invalid");
					} else {
						$(field).addClass("invalid");
					}
				}
				
			}

			// если поле невалидно - невалидна вся форма
			// но цикл нужно пройти до конца, чтобы подсветить невалидные поля
			if (!is_field_valid) {
				is_valid = false
			}
		}
		
		if (!is_valid) {
			t.submit.addClass("inactive")
		} else {
			t.submit.removeClass("inactive")
		}
		
		return t.is_valid = is_valid;
	},
	
	/**
	 * @param {String} text
	 */
	"validate-as-text": function(text){
		var valid = true
		if (text.length < 4) {
			valid = false
		}
		return valid
	},
	
	"validate-as-name": function(name){
		var valid = true
		if (name.length < 2) {
			valid = false
		}
		return valid
	},
	
	"validate-as-email": function(email){
		var emailRe = new RegExp("^[^\\s()<>@,;:\\/]+@\\w[\\w\\.-]+\\.[a-z]{2,}$", "i")
		return emailRe.test(email)
	},
	
	"validate-as-phone": function(phone){
		var phoneRe = /[0-9,\+,\-,\s,\(,\)]{7,}/i
		return phoneRe.test(phone)
	}
}

$(function(){
	var css_text = CSSFlagGenerator.generate()
	
	if (document.createStyleSheet) {
		var ss = document.createStyleSheet()
		ss.disabled = true
		ss.cssText = css_text
		ss.disabled = false
	} else {
		var ss = document.createElement("style")
		var text = document.createTextNode(css_text)
		try {
			ss.setAttribute("type", "text/css")
			ss.appendChild(text)
		} catch (e) {
			try {
				var l = document.createElement("link")
				l.setAttribute("rel", "stylesheet")
				l.setAttribute("href", "/css/flags.css")
				document.getElementsByName("head")[0].appendChild(l)
			} catch (e) {
				//тотал еггог 
			}
		}
		document.documentElement.appendChild(ss)
	}
})

$(function(){
	var tabbed_class = "tabbed-section"
	$(".section").each(function(){
		var section = $(this)
		var tabs = $("> .section-layout > .center > .tabs", section)
		if (tabs.length) {
			if (!section.hasClass(tabbed_class)) {
				section.addClass(tabbed_class)
			}
		}
	})
})


$(function(){
	$(".create-toc").each(function(){
		new TOC(this)
	})

	$(".create-toc2").each(function(){
		new TOC(this, 2)
	})
	
	if ($.fn.lightBox) {
		$(".gallery a").lightBox()
	}
	
	$(".opencontainer").click(function(){
		var container = $(this).parent()
		if (container.hasClass("opened")){
			container.animate({top: 278}, 220).removeClass("opened");
		} else {
			container.animate({top: 0}, 220, function(o){
				container.find("input")[0].focus()
				container.addClass("opened")
			});
		}
		return false	
	})
	
	$(".apply-validator").each(function(){
		new FormValidator(this)
	})
})














