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();
}

// -----------------------------------
//  Все 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);
	}
}

var infoBlockVisible = false;

var infoBlockTimeOut;

function gallery_category_view(data, opts) {

    if($.browser.msie && ($.browser.version < "8.0")) {
        var id = data.request.get.id;
        var view = data.request.get.view;
        window.location = "/gallery/" + view + "/" + id + "/";
        return false;
    }

    $("#box").html(data.html);
    $("#overlay").fadeIn();
    $("#box").fadeIn();
    $("#box").css("top", $(document).scrollTop() + 30 + "px");

    $(".box-list").jCarouselLite({
        btnPrev: ".box-list-c .box-list-next",
        btnNext: ".box-list-c .box-list-prev",
        vertical: true,
        mouseWheel: true,
        visible: 4,
        scroll: 2
    });

    $(".box-list img").click(function(){
        $(".box-list li").removeClass("selected");
        $(this).parents().map(function(){
            if(this.tagName == "A") {
                $(".box-main img").attr("src", $(this).attr("href"));
                $(".info-c .info .desc").html($(this).attr("title"));
            }
            if(this.tagName == "LI") {
                var clss = this.className;
                $("." + clss).addClass("selected");
            }
        });
        return false;
    });
/*
    $("#overlay").animate({
        opacity: 0.7
    });

    $(".info-c .info").animate({
        opacity: 0.8
    }, 300);
*/
    $(".info-c .info .icon.close").hide();

    $(".info-c .info .icon.open").click(function(){
        $(".info-c .info").animate({
            left: "400px"/*,
            opacity: 0.8*/
        }, 300);
        $(this).hide();
        $(".info-c .info .icon.close").show();
    });

    $(".info-c .info .icon.close").click(function(){
        $(".info-c .info").animate({
            left: "750px"/*,
            opacity: 0.4*/
        }, 300);
        $(this).hide();
        $(".info-c .info .icon.open").show();
    });
/*
    $(".box-main .box-list-prev, .box-main .box-list-next").animate({
        opacity: 0.5
    }, 200);

    $(".box-main .box-list-prev, .box-main .box-list-next").hover(
        function(){
            $(this).animate({
                opacity: 1
            }, 200);
        },
        function(){
            $(this).animate({
                opacity: 0.5
            }, 200);
        }
    );
*/
    $(".box-main .box-list-prev").click(function(){
        $(".box-list li.selected").prev().children().map(function(){
            if(this.tagName == "A") {
                $(this).children().map(function(){
                    $(this).click();
                });
            }
        });
        return false;
    });

    $(".box-main .box-list-next").click(function(){
        $(".box-list li.selected").next().children().map(function(){
            if(this.tagName == "A") {
                $(this).children().map(function(){
                    $(this).click();
                });
            }
        });
        return false;
    });
    
}

function gallery_category_view_err(data) {
}

function flashmap_view(data) {
	$("#dialog .inner").html(data.html);
	dialogShow();
}

function realestate_question(data) {
	$("#dialog .inner").html(data.html);
	dialogShow();
}

function realestate_question_posted_err(data) {
	if(data.sys.error.type == "success") {
		$("#realestateQuestionForm .message").fadeIn(300);
		setTimeout(function() {
			$("#realestateQuestionForm .message").fadeOut(300);
			dialogHide();
		}, 3000);
	}
}

// Ошибки

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 'realestate': {
			
			switch(params['view']) {
				
				case 'question': {
					
					switch(params['action']) {
						
						case 'post': {
							postData += getFormData('realestateQuestionForm');
							func = "realestate_question_posted";
							funcErr = "realestate_question_posted_err";
						} break;
		
						default: {
							func = "realestate_question";
							funcErr = "realestate_question_err";
						} break;
		
					}

				} break;
				
				default: break;
			}

		} break;

		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 'gallery': {
			
			switch(params['view']) {
				
				case 'category': {
					func = "gallery_category_view";
					funcErr = "gallery_category_view_err";
				} break;
				
				default: break;
			}

		} break;
		
		case 'flashmap': {
			
			func = "flashmap_view";
			funcErr = "flashmap_view_err";

		} 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;

}


