// JavaScript Document
function Load(){
	assign_above_menu_effects();
	assign_sub_menu_effects();
	assign_events();
	init_dw_Scroll();
	modal_drag_drop();
	set_phone_mark();
	update_models();
	set_header();
	add_banners();
	add_big_banner();
}

function Load_content(){
	assign_above_menu_effects();
	assign_sub_menu_effects();
	assign_events();
	modal_drag_drop();
	set_phone_mark();
	update_models();
	set_header();
	add_banners();	
	set_trans_z();
	set_lang_change_urls();
}

function Load_inner(){
	assign_above_menu_effects();
	assign_sub_menu_effects();
	assign_events();
	modal_drag_drop();
	set_phone_mark();
	update_models();
	set_header();
	add_banners();
	set_content_height();
	set_lang_change_urls();	
}

function assign_events(){
	$('query').observe('keyup', handlerSearch);
}

function handlerSearch(event){
	var element_ = event.element();	
	keyCode_ = parseInt(event.keyCode);
	value_ = element_.value;
	
	if(keyCode_ == 13){
		search();
	}	
}

function set_trans_z(){
	p_height = parseInt($('p_text').getHeight());
	$('text_container').style.height = String(p_height)+'px';
}

function set_lang_change_urls(){
	current_url = new String(location.href);
	
	$('first').href = current_url.replace('/ru/', '/az/');
	$('second').href = current_url.replace('/ru/', '/en/');	
}

function search(){
	query_ = $('query').value;
	if(query_.length>=4){
		if(/[0-9]/.match(query_)>0){
			a_params = '&search_field=code';
	    }
		else{
			a_params = '&search_field=name';
		}
		
		a_params += '&type=M';
		
		location.href = 'search.php?query='+query_+a_params;
	}
	else{
		messageBox('Искомое слово должно быть не менее 4-х символов');
	}
}

function set_content_height(){
	content_height = parseInt($('div_content').getHeight());	
	groups_height = parseInt($('groups').getHeight());
	
	if((groups_height+95)>content_height){
		height = groups_height;
	}
	else{
		height = content_height;
	}
	
	$('content_container').style.height = new String(height+185)+'px';
	$('content').style.height = new String(height)+'px';
	$('groups').style.height = new String(height-30)+'px';
}

function set_header(){
	var banner = new SWFObject("flash/flash-2.swf", "default", "550", "246", "9");
	banner.addParam("wmode", "transparent");
    banner.write('8787_banner');
}

function add_banners(){
	var zengim_banner = new SWFObject("flash/zengim.swf", "default", "433", "97", "9");
	zengim_banner.addParam("wmode", "transparent");
	zengim_banner.write("zengim_banner");
	
	var fun_business_banner = new SWFObject("flash/fun_business.swf", "default", "433", "97", "9");
	fun_business_banner.addParam("wmode", "transparent");
	fun_business_banner.write("fun_business_banner");
}

function add_big_banner(){
	var big_banner = new SWFObject("flash/8787.swf", "default", "590", "163", "9");
	big_banner.addParam("wmode", "transparent");
	big_banner.write("big_banner");
}

function set_phone_mark(){
	
	for(i=0;i<$('phones').options.length-1;i++){
		id = parseInt($('phones').options[i].value);
		if(id == mark_id){
			$('phones').options[i].selected=true;
		}
	}
}

function modal_drag_drop(){
	var theHandle = $("panel");
	var theRoot = $("mp3_modal");
	Drag.init(theHandle, theRoot);
	
	Drag.init($('modal_box'));
}

function init_dw_Scroll() {
    var wndo_themes = new dw_scrollObj('tmc', 'tmb', 'tm');
    wndo_themes.setUpScrollControls('scrollLinks');
	wndo_themes.setUpScrollControls('extracontrolst');
	
	var wndo_games = new dw_scrollObj('gmc', 'gmb', 'gc');
    wndo_games.setUpScrollControls('scrollLinks_game');
	wndo_games.setUpScrollControls('extracontrolg');
	
	var wndo_bestpictures = new dw_scrollObj('bmc', 'bmb', 'bc');
    wndo_bestpictures.setUpScrollControls('bpcontrols');
	wndo_bestpictures.setUpScrollControls('extracontrolp');
	
	var wndo_books = new dw_scrollObj('bookmc', 'bookmb', 'bookc');
    wndo_books.setUpScrollControls('scrollcontrolsbook');
	wndo_books.setUpScrollControls('extracontrolsbook');
	
	var wndo_video = new dw_scrollObj('videomc', 'videomb', 'videoc');
    wndo_video.setUpScrollControls('scrollcontrolsvideo');
	wndo_video.setUpScrollControls('extracontrolsvideo');
	
	var wndo_mp3 = new dw_scrollObj('wn', 'lyr1');
	wndo_mp3.setUpScrollControls('mp3controls');
	
	var wndo_zengim = new dw_scrollObj('wn2', 'lyr2');
	wndo_zengim.setUpScrollControls('zengimcontrols');
}

function set_phoneModel(object){
	
	if(object.value>0){
	
		variables = {
		'phone_id': object.value,
		'mark': $('phones').value
		}
		
		JsHttpRequest.query('set.phone_session.php',variables,js_response,true);	
	}
}

function js_response(result, errors){
	if(result['message']!=null){
		messageBox(result['message']);
	}
}

function assign_above_menu_effects(){
	imgs = document.getElementById("navigation").getElementsByTagName("img");
	
	for(i=0;i<imgs.length;i++){
		imgs[i].onmouseover = function(){
			source = this.src;
			source = source.replace('.gif', '(hover).gif');
			this.src = source;
		}
		
		imgs[i].onmouseout = function(){
			source = this.src;
			source = source.replace('(hover)', '');
			this.src = source;
		}
	}
}

function assign_sub_menu_effects(){
	divs = document.getElementById("sub_navigation").getElementsByTagName("div");
	for(i=0;i<divs.length;i++){
		//divs[i].parentNode.style.background = 'white';
		
		divs[i].onmouseover = function(){
			
			img = this.getElementsByTagName('img'); 
			
			//check if disabled
			disabled = img[0].getAttribute("isdis");
			
			if(disabled==0){
				this.className= 'sub_menu_bg_hover';
				source = img[0].src; source = source.replace('.gif', '(hover).gif');
				img[0].src = source;
				
				this.parentNode.style.background = "url('pictures/alt_menu_corner(hover).gif')";
				this.parentNode.style.backgroundRepeat = 'no-repeat';
				this.parentNode.style.backgroundPosition = 'right';
			}
		}
		
		divs[i].onmouseout = function(){			
			img = this.getElementsByTagName('img');
			
			//check if disabled
			disabled = img[0].getAttribute("isdis");
			if(disabled==0){
				this.className = 'sub_menu_bg';
				source = img[0].src; source = source.replace('(hover)', '');
				img[0].src = source;
				
				this.parentNode.style.background = "url('pictures/alt_menu_corner.gif')";
				this.parentNode.style.backgroundRepeat = 'no-repeat';
				this.parentNode.style.backgroundPosition = 'right';
			}
		}
	}
}

function update_models(){
	variables = {
	'phone_id':$('phones').value
	}
	
	JsHttpRequest.query(
	'get.models.json.php',
	variables,
	function(result, errors){
		if(result['phone_list']!=null){
			list = result['phone_list'];
			
			selectname = 'models';
			
			object_list = new Object();		  	
			//clear list
			$(selectname).options.length=0;
				
			for(keyVar in object_list){
				object_list[keyVar] = '';
			}
			//Inserting values
			eval(list);
			
			phone_id = object_list['phone_id'];
			
			delete object_list['phone_id'];
						
			counter = 0;
			for(keyVar in object_list){
				$(selectname).options[counter] = new Option(object_list[keyVar], keyVar);
				if(keyVar == phone_id) $(selectname).options[counter].selected = true;
				counter++;				
			}
				
			//enable
			$(selectname).disabled = false;
		}
	}
	,
	true
	);
}

function hide_phone_select(){	
	if(BrowserDetect.browser=="Explorer" && BrowserDetect.version == "6"){
		$('phones').style.visibility = 'hidden';
		$('models').style.visibility = 'hidden';
	}
}

function show_phone_select(){
	if(BrowserDetect.browser=="Explorer" && BrowserDetect.version == "6"){
		$('phones').style.visibility = '';
		$('models').style.visibility = '';
	}
}

function showModal(url){
	getelementbyid('n_lay').style.display = 'block';
	getelementbyid('region').src = url;
	center(getelementbyid('n_lay'));
}

function modal_close(){
	$('mp3_modal').style.display = 'none';
	$('player').src = 'preview.html';
	show_phone_select();
}

function close_modal_box(){
	$('modal_box').style.display = 'none';
}

function messageBox(text){
	$('msg').innerText = text;
	$('modal_box').style.display = 'block';
	center($('modal_box'));
}

function loadSound(music_id){		
	url = 'preview.php?id='+music_id;
	showModal(url);
}

function ringtone_details(music_id){
	url = 'preview.php?id=z'+music_id;
	showModal(url);
}

function music_details(music_id){		
	url = 'preview.php?id='+music_id;
	showModal(url);
}

function video_details(content_id){
	url = 'video.preview.php?id='+content_id;
	showModal(url);
}

function theme_details(content_id){
	url = 'theme.preview.php?id='+content_id;
	showModal(url);
}

function game_details(content_id, l){
	url = 'info.php?l='+ l + '&id=' + content_id;
	showModal(url);
}

function game_details_theme(content_id, l){
	url = 'info_theme.php?l='+ l + '&id=' + content_id;
	showModal(url);
}

function book_details(content_id){
	url = 'book.preview.php?id='+content_id;
	showModal(url);
}

function picture_details(content_id){
	url = 'picture.preview.php?id='+content_id;
	showModal(url);
}

function center(object){
		var my_width  = 0;
		var my_height = 0;
		
		if ( typeof( window.innerWidth ) == 'number' ){
			my_width  = window.innerWidth;
			my_height = window.innerHeight;
		} else if ( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ){
			my_width  = document.documentElement.clientWidth;
			my_height = document.documentElement.clientHeight;
		} else if ( document.body && ( document.body.clientWidth || document.body.clientHeight ) ){
			my_width  = document.body.clientWidth;
			my_height = document.body.clientHeight;
		}
		
		object.style.position = 'absolute';
		object.style.zIndex = 99;
		
		var scrollY = 0;
		
		if ( document.documentElement && document.documentElement.scrollTop ){
			scrollY = document.documentElement.scrollTop;
		}else if ( document.body && document.body.scrollTop ){
			scrollY = document.body.scrollTop;
		}else if ( window.pageYOffset ){
			scrollY = window.pageYOffset;
		}else if ( window.scrollY ){
			scrollY = window.scrollY;
		}
		
		
		var setX = ( my_width  -  660 ) / 2;
		var setY = ( my_height -  362 ) / 2 + scrollY-50;
		
		setX = ( setX < 0 ) ? 0 : setX;
		setY = ( setY < 0 ) ? 0 : setY;
		
		object.style.left = setX + "px";
		object.style.top  = setY + "px";
		
}

function subscribe_user(){
	email_ = $('email').value;
	
	if(email_.length>0){
		if(emailCheck(email_)){
			variables = {
			'email':email_
			}
			
			JsHttpRequest.query(
				'subscribe.php',
				variables,
				function(result, errors){
					if(result['message']!=null){
						messageBox(result['message']);
					}
				},
				true
			);
		}
	}
	
}


function emailCheck (emailStr) {
/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */
var emailPat=/^(.+)@(.+)$/
/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address. 
   These characters include ( ) < > @ , ; : \ " . [ ]    */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
/* The following string represents the range of characters allowed in a 
   username or domainname.  It really states which chars aren't allowed. */
var validChars="\[^\\s" + specialChars + "\]"
/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")"
/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
/* The following string represents an atom (basically a series of
   non-special characters.) */
var atom=validChars + '+'
/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")"
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


/* Finally, let's start trying to figure out if the supplied address is
   valid. */

/* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */
	messageBox("Ваш маил неправильный (проверьте сиволы @, .)")
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid 
if (user.match(userPat)==null) {
    // user is not valid
    messageBox("Имя пользователя неправильно.")
    return false
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        messageBox("IP указанный в вашем маиле!")
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	messageBox("Название домена неправильное.")
    return false
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding 
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
   messageBox("Конец имени домена не может окончиваться более чем на три буквы.")
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="В адресе отсутствует имя хоста!"
   messageBox(errStr)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}

//===================================//
// Browser Detect
//===================================//
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

BrowserDetect.init();