/*
** Функция возвращат объект XMLHttpRequest
*/
function getXmlHttpRequest()
{
	if (window.XMLHttpRequest) 
	{
		try 
		{
			return new XMLHttpRequest();
		} 
		catch (e){}
	} 
	else if (window.ActiveXObject) 
	{
		try 
		{
			return new ActiveXObject('Msxml2.XMLHTTP');
		} catch (e){}
		try 
		{
			return new ActiveXObject('Microsoft.XMLHTTP');
		} 
		catch (e){}
	}
	return null;
}
//JSON
if (!this.JSON) {

    JSON = function () {

        function f(n) {    // Format integers to have at least two digits.
            return n < 10 ? '0' + n : n;
        }

        Date.prototype.toJSON = function () {

            return this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z';
        };


        var m = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };

        function stringify(value, whitelist) {
            var a,          // The array holding the partial texts.
                i,          // The loop counter.
                k,          // The member key.
                l,          // Length.
                r = /["\\\x00-\x1f\x7f-\x9f]/g,
                v;          // The member value.

            switch (typeof value) {
            case 'string':

                return r.test(value) ?
                    '"' + value.replace(r, function (a) {
                        var c = m[a];
                        if (c) {
                            return c;
                        }
                        c = a.charCodeAt();
                        return '\\u00' + Math.floor(c / 16).toString(16) +
                                                   (c % 16).toString(16);
                    }) + '"' :
                    '"' + value + '"';

            case 'number':

                return isFinite(value) ? String(value) : 'null';

            case 'boolean':
            case 'null':
                return String(value);

            case 'object':

                if (!value) {
                    return 'null';
                }

                if (typeof value.toJSON === 'function') {
                    return stringify(value.toJSON());
                }
                a = [];
                if (typeof value.length === 'number' &&
                        !(value.propertyIsEnumerable('length'))) {

                    l = value.length;
                    for (i = 0; i < l; i += 1) {
                        a.push(stringify(value[i], whitelist) || 'null');
                    }

                    return '[' + a.join(',') + ']';
                }
                if (whitelist) {

                    l = whitelist.length;
                    for (i = 0; i < l; i += 1) {
                        k = whitelist[i];
                        if (typeof k === 'string') {
                            v = stringify(value[k], whitelist);
                            if (v) {
                                a.push(stringify(k) + ':' + v);
                            }
                        }
                    }
                } else {

                    for (k in value) {
                        if (typeof k === 'string') {
                            v = stringify(value[k], whitelist);
                            if (v) {
                                a.push(stringify(k) + ':' + v);
                            }
                        }
                    }
                }

                return '{' + a.join(',') + '}';
            }
        }

        return {
            stringify: stringify,
            parse: function (text, filter) {
                var j;

                function walk(k, v) {
                    var i, n;
                    if (v && typeof v === 'object') {
                        for (i in v) {
                            if (Object.prototype.hasOwnProperty.apply(v, [i])) {
                                n = walk(i, v[i]);
                                if (n !== undefined) {
                                    v[i] = n;
                                }
                            }
                        }
                    }
                    return filter(k, v);
                }


                if (/^[\],:{}\s]*$/.test(text.replace(/\\./g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(:?[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

                    j = eval('(' + text + ')');

                    return typeof filter === 'function' ? walk('', j) : j;
                }

                throw new SyntaxError('parseJSON');
            }
        };
    }();
}
//Drag & Drop
var dragMaster = (function() {

	var dragObject
	var mouseOffset

	// получить сдвиг target относительно курсора мыши
	function getMouseOffset(target, e) {
		var docPos	= getPosition(target)
		return {x:e.pageX - docPos.x, y:e.pageY - docPos.y}
	}

	function mouseUp(e){
		var html = document.documentElement;
		var body = document.body;
		var pos = dragObject.style.top
		if(dragObject.style.position == 'absolute'){
		dragObject.style.position = 'fixed';
		dragObject.style.top = (Number(pos.substr(0,pos.length-2)) - html.scrollTop - body.scrollTop)+'px';		
		}
		dragObject = null

		// очистить обработчики, т.к перенос закончен
		document.onmousemove = null
		document.onmouseup = null
		document.ondragstart = null
		document.body.onselectstart = null
	}

	function mouseMove(e){
		e = fixEvent(e)
		var html = document.documentElement;
		var body = document.body;
		with(dragObject.style) {
			position = 'absolute'
			var browser = navigator.appName;
			if(browser == 'Opera' || browser == 'Microsoft Internet Explorer'){
				top = e.pageY - mouseOffset.y + 'px'
			}else{
				//top = e.pageY - mouseOffset.y + body.scrollTop + 'px'
				top = e.pageY - mouseOffset.y - html.scrollTop + 'px';
			}
			left = e.pageX - mouseOffset.x + 'px'
		}
		return false
	}

	function mouseDown(e) {
		e = fixEvent(e)
		if (e.which!=1) return

		dragObject = document.getElementById('message_box');
		//dragObject  = this

		// получить сдвиг элемента относительно курсора мыши
		mouseOffset = getMouseOffset(this, e)

		// эти обработчики отслеживают процесс и окончание переноса
		document.onmousemove = mouseMove
		document.onmouseup = mouseUp

		// отменить перенос и выделение текста при клике на тексте
		document.ondragstart = function() { return false }
		document.body.onselectstart = function() { return false }

		return false
	}

	return {
		makeDraggable: function(element){
			element.onmousedown = mouseDown
		}
	}

}())

function getPosition(e){
	var left = 0
	var top  = 0
	var html = document.documentElement;
	var body = document.body;
	while (e.offsetParent){
		left += e.offsetLeft + html.scrollLeft + body.scrollLeft;
		top  += e.offsetTop + html.scrollTop + body.scrollTop;
		e	 = e.offsetParent
	}

	left += e.offsetLeft
	top  += e.offsetTop

	return {x:left, y:top}
}
function fixEvent(e) {
	// получить объект событие для IE
	e = e || window.event

	// добавить pageX/pageY для IE
	if ( e.pageX == null && e.clientX != null ) {
		var html = document.documentElement
		var body = document.body
		e.pageX = e.clientX + (html && html.scrollLeft || body && body.scrollLeft || 0) - (html.clientLeft || 0)
		e.pageY = e.clientY + (html && html.scrollTop || body && body.scrollTop || 0) - (html.clientTop || 0)
	}

	// добавить which для IE
	if (!e.which && e.button) {
		e.which = e.button & 1 ? 1 : ( e.button & 2 ? 3 : ( e.button & 4 ? 2 : 0 ) )
	}

	return e
}
//Ajax
function send(){
	var name = document.getElementById('form_name');
	var phone = document.getElementById('form_phone');
	var message = document.getElementById('form_message');
	if(name.value == '' || name.value == 'Введите ваше имя'){
		name.value = 'Введите ваше имя';
		name.style.color = 'red';
		return false;
	}
	if(phone.value == '' || phone.value == 'Введите телефон'){
		phone.value = 'Введите телефон';
		phone.style.color = 'red';
		return false;
	}
	var order = new Object();
	order.name = name.value;
	order.message = message.value;
	order.phone = phone.value;
	order.address = String(window.location);
	var jsonData = JSON.stringify(order);
	var req = getXmlHttpRequest();
	req.onreadystatechange = function(){
		if (req.readyState != 4) return;
			$('#message_box').fadeOut(500);
			$('#message_send').css({"top": ($(window).height() - $('#message_send').height() ) / 2+'px',
			"left": ($(window).width() - $('#message_send').width() ) / 2+'px'}).fadeIn(500);
		}
	req.open("POST", "send.php", true);
	req.setRequestHeader("Content-Type", "text/plain");
	req.setRequestHeader("Content-Length", jsonData.length);
	req.send(jsonData);	
	return false;
}
window.onload = function(){
	$('#form_close').click(function(){
		$('#message_box').fadeOut(500);
	});
	$('#close_message_send').click(function(){
		$('#message_send').fadeOut(500);
	});
	$('#form_open').click(function(){
		$('#message_box').css({"top": ($(window).height() - $('#message_box').height() ) / 2+'px',
			"left": ($(window).width() - $('#message_box').width() ) / 2+'px'}).fadeIn(500);
				return false;
	});
	//Вторая ссылка
	$('#form_open2').click(function(){
		$('#message_box').css({"top": ($(window).height() - $('#message_box').height() ) / 2+'px',
			"left": ($(window).width() - $('#message_box').width() ) / 2+'px'}).fadeIn(500);
				return false;
	});

	var dragObject = document.getElementById('contact-title');    
    dragMaster.makeDraggable(dragObject);
	
	var submit = document.getElementById('form_submit');
	if(submit){
		submit.onclick = send;
	}
	
	$('#form_name').focus(function(){
		if($(this).val() == 'Введите ваше имя'){
			$(this).val('');
			$(this).css({'color':''});
		}
	})
	$('#form_name').blur(function(){
		if($(this).val() == ''){
			$(this).val('Введите ваше имя');
			$(this).css({'color':'red'});
		}
	})
	
	$('#form_phone').focus(function(){
		if($('#form_name').val == ''){
			$('#form_name').val('Введите ваше имя');
			$('#form_name').css({'color':'red'});
		}
		if($(this).val() == 'Введите телефон'){
			$(this).val('');
			$(this).css({'color':''});
		}
	})
	
	$('#form_phone').blur(function(){
		if($(this).val() == ''){
			$(this).val('Введите телефон');
			$(this).css({'color':'red'});
		}
	})
	$('#form_message').focus(function(){
		if($('#form_name').val == ''){
			$('#form_name').val('Введите ваше имя');
			$('#form_name').css({'color':'red'});
		}
		if($('#form_phone').val == ''){
			$('#form_phone').val('Введите телефон');
			$('#form_phone').css({'color':'red'});
		}
	})
}













