var jsParams = {
	dialog_bg_opacity: 85,
	errors_close_time: 100,
	loader_open_time: 150,
	loader_close_time: 150,
	dialog_close_time: 150,
	dialog_open_time: 150
}

// -----------------------------------
//  php
// -----------------------------------

function call_user_func_array( strFunctionName , arrParam ){
    var strCommand = "";
    var i;
    strCommand += "return " + strFunctionName + "(";
    for( i = 0; i < arrParam.length; ++i ) {
        strCommand += "arrParam[" + i + "]" ;
        if( ( i + 1 ) != arrParam.length ) {
            strCommand += ",";
        }
    }
    strCommand += ")";
    var oFunction = new Function( "arrParam" , strCommand );
    return oFunction( arrParam );
}

function isSet(name){
	return !(typeof document.all[name] == "undefined");
}

// -----------------------------------
//  Обрабатываем загрузку страницы
// -----------------------------------

$(document).ready(function(){


});

// Другие функции

function check(string, type) {
	switch(type) {
		case 'string':
			var reg=/^[a-zA-Zа-яА-Я\-_ \s]+$/
			break;
		case 'num':
			var reg=/^[0-9\s]+$/
			break;
		case 'email':
			var reg=/^([a-z,0-9,_,\-,\.])+\@([a-z,0-9,_,\-])+(\.([a-z,0-9])+)+$/
			break;
		case 'phone':
			var reg=/(?:8|\+7)? ?\(?(\d{3})\)? ?(\d{3})[ -]?(\d{2})[ -]?(\d{2})/
			break;
		default: break;
	}
	alert(reg.test(string));
}

function getFormData(id) {
	var data = "";
	$("#"+id+" :input").map(function() {
		var key = 1;
		if($(this).attr('type') == 'checkbox' || $(this).attr('type') == 'radio')
			if(!$(this).attr('checked'))
				key = 0;
		if(key) {
			data += $(this).attr('name') + "=" + $(this).val() + "&";
		}
	});
	return data;
}

function clearForm(id) {
	$("#"+id+" :reset").click();
}

function setCookie(name, value, expiredays, path, domain, secure) {
	if (expiredays) {
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+expiredays);
		var expires = exdate.toGMTString();
	}
	document.cookie = name + "=" + escape(value) +
	((expiredays) ? "; expires=" + expires : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
}

function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset);
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return setStr;
}

// -----------------------------------
//  Все ajax функции
// -----------------------------------

function faq_posted(data) {
}

function faq_posted_err(data) {
	if(data.sys.error.type == "success") {
		clearForm('faqPostForm');
		$("#faqPostForm .message").fadeIn(300);
		setTimeout(function() {
			$("#faqPostForm .message").fadeOut(300);
		}, 5000);
	}
}

function contact_posted(data) {
}

function contact_posted_err(data) {
	if(data.sys.error.type == "success") {
		clearForm('contactPostForm');
		$("#contactPostForm .message").fadeIn(300);
		setTimeout(function() {
			$("#contactPostForm .message").fadeOut(300);
		}, 5000);
	}
}

function request_posted(data) {
}

function request_posted_err(data) {
	if(data.sys.error.type == "success") {
		clearForm('requestPostForm');
		$("#requestPostForm .message").fadeIn(300);
		setTimeout(function() {
			$("#requestPostForm .message").fadeOut(300);
		}, 5000);
	}
}

// Ошибки

var errorsCh = 0;

function errHappens(data) {
	$("#errorsC ul").append("<li id=\"error" + errorsCh + "\" class=\"error\" onclick=\"return false;\">" + data.html + "</li>");
	setTimeout(function() {
	}, 5000);
	errorsCh++;
}

function errEmpty() {
	$("#errorsC ul").empty();
}

function errClose(obj) {
	var parentEls = $(obj).parents().map(function() { 
		if(this.className == "error") {
			$("#" + this.id).fadeOut(jsParams['errors_close_time']);
			return false;
		}
	});
}

// Функция загрузки ajax страницы

function page(page, params, opts) {
	
	errEmpty();
	
	$("#loader").fadeIn(jsParams['loader_open_time']);

	var func;
	var funcErr;
	var getData = "";
	var postData = "";

	if(params)
		for(var key in params)
			getData += key + "=" + params[key] + "&";
	else
		params = "";
	if(!opts)
		opts = "";

	switch(page) {

		case 'faq': {
			
			switch(params['action']) {
				
				case 'post': {
					postData += getFormData('faqPostForm');
					func = "faq_posted";
					funcErr = "faq_posted_err";
				} break;
				
				default: break;
			}

		} break;
		
		case 'contact': {
			
			switch(params['action']) {
				
				case 'post': {
					postData += getFormData('contactPostForm');
					func = "contact_posted";
					funcErr = "contact_posted_err";
				} break;
				
				default: break;
			}

		} break;
		
		case 'request': {
			
			switch(params['action']) {
				
				case 'post': {
					postData += getFormData('requestPostForm');
					func = "request_posted";
					funcErr = "request_posted_err";
				} break;
				
				default: break;
			}

		} break;

		default: return true;
		
	}
	
	$.ajax({
		type: "POST",
		url: "/index.php?page=" + page + "&" + getData + "ajax",
		data: postData,
		success: function(html) {
			//alert(html);
			var info = eval( '(' + html + ')' );
			if(info.sys.error.id) {
				if(funcErr)
					call_user_func_array(funcErr, [info, opts]);
				errHappens(info);
			}
			else {
				if(info.request.redirect)
					window.location = info.request.redirect;
				call_user_func_array(func, [info, opts]);
			}
		}
	});

	$("#loader").fadeOut(jsParams['loader_close_time']);

	return false;

}


