
function MGsetCookie( name, value, path, domain, time ) {
    var secure = '';
    var today = new Date();
    today.setTime( today.getTime() );
    if (time == ''){
        expires = 1 * 1000 * 60 * 60 * 6;
    } else expires = 1 * 1000 * 60 * 60 * time;

    var expires_date = new Date( today.getTime() + (expires) );

    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}
function MGgetCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

var MG_domen = (location.href.indexOf(".net") > 0) ? '.marketgid.net' : '.marketgid.com';

/*
var ua = navigator.userAgent.toLowerCase();

    // Opera
var isOpera = (ua.indexOf("opera") != -1);
    // Определим Internet Explorer
var isIE = (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1 && ua.indexOf("webtv") == -1);

    // Gecko = Mozilla + Firefox + Netscape
var isGecko = (ua.indexOf("gecko") != -1);

var timepop1 = 1;
var timepop2 = 10/60/60;
var popunder1_ff = 'http://marketgid.ru/smi.marketgid.com.html';
var popunder1_o = 'http://marketgid.ru/oo.smi.marketgid.com.html';
var popunder1_ie6 = 'http://marketgid.com/i6.smi.marketgid.com.html';
var popunder1_ie7 = 'http://marketgid.com/i7.smi.marketgid.com.html';
var popunder2 = 'http://topnews.dt00.net/red-hot-digest-ru.html';
var popunder1_other = 'http://marketgid.com/other.smi.marketgid.com.html';

function mgopen(event){
    global:timepop1,timepop2,popunder1_ff, popunder2;
    global:MG_domen;
    if (document.cookie == '' || navigator.userAgent.toLowerCase().indexOf('linux') > 0) return;
    if (isGecko){
        if (event.button==2) return;
        if (!MGgetCookie('MG_popunder')){
            MGsetCookie('MG_popunder', 1, '/', MG_domen, timepop1);
            MGsetCookie('MG_popunder2', 1, '/', MG_domen, timepop2);
            MGsetCookie('MG_popunder3', 0, '/', MG_domen, 0);
            window.open(popunder1_ff ,'tr','fullscreen=0,toolbar=1,location=1,status=1, menubar=1,scrollbars=1,resizable=1');
            self.focus();
        }
        if (MGgetCookie('MG_popunder') && !MGgetCookie('MG_popunder2') && !parseInt(MGgetCookie('MG_popunder3'))){
            MGsetCookie('MG_popunder3', 1, '/', MG_domen, timepop1 - timepop2);
            window.open(popunder2 ,'tr1','toolbar=1,location=1,status=1, menubar=1,scrollbars=1,resizable=1');
            self.focus();
        }
    }
}
*/
// Скрипты для комментариев

function isHiddenEditor() {
    return typeof(tinyMCE) == 'undefined' || !tinyMCE.getInstanceById('comment') ? true : false;
}

function quoteComment(commentId, commentText) {
    var posttext = '';

    if (window.getSelection) {
        posttext = window.getSelection();
        if (posttext != '' && window.getSelection().containsNode) {
            commentNode = document.getElementById('commentContent-' + commentId);
            if (!window.getSelection().containsNode(commentNode, true)) {
                commentId = 0;
            }
        }
    } else if (document.getSelection) {
        posttext = document.getSelection();
    } else if (document.selection) {
        posttext = document.selection.createRange().text;
    }

    if (posttext == '') {
        posttext = commentText;
    }

    quoteInsert(commentId, '[cite' + (commentId ? ' id=' + commentId : '') + ']' + posttext + '[/cite]\n');
    return false;
}

function quoteSelection() {
    var posttext = '';

    if (window.getSelection) {
        posttext = window.getSelection();
    } else if (document.getSelection) {
        posttext = document.getSelection();
    } else if (document.selection) {
        posttext = document.selection.createRange().text;
    } else {
        return true;
    }

    if (posttext == '') {
        alert('Выделите текст для цитирования');
        return true;
    } else {
        quoteInsert(0, '[cite]' + posttext + '[/cite]\n');
    }

    return false;
}

function quoteInsert(commentId, text) {

    showCommentForm();

    comment = document.getElementById('comment');
    if (!comment) {
        return false;
    }

    if (!isHiddenEditor()) {
        if (commentId) {
            document.getElementById('comment_parent_id').value = commentId;
        }
        tinyMCE.execCommand('mceInsertContent', false, text + "\n");
        tinyMCE.execCommand('mceFocus', false, 'comment');
        return true;
    }

    // IE support
    if (document.selection) {
        comment.focus();
        sel = document.selection.createRange();
        sel.text = text;
        comment.focus();
    }
    // MOZILLA/NETSCAPE support
    else if (comment.selectionStart || comment.selectionStart == '0') {
        var startPos = comment.selectionStart;
        var endPos = comment.selectionEnd;
        var cursorPos = endPos;
        var scrollTop = comment.scrollTop;
        if (startPos != endPos) {
            comment.value = comment.value.substring(0, startPos)
                          + text
                          + comment.value.substring(endPos, comment.value.length);
            cursorPos = startPos + text.length
        }
        else {
            comment.value = comment.value.substring(0, startPos)
                              + text
                              + comment.value.substring(endPos, comment.value.length);
            cursorPos = startPos + text.length;
        }
        comment.focus();
        comment.selectionStart = cursorPos;
        comment.selectionEnd = cursorPos;
        comment.scrollTop = scrollTop;
    }
    else {
        comment.value += text;
        comment.focus();
    }

    if (commentId) {
        document.getElementById('comment_parent_id').value = commentId;
    }

    return true;
}

function isCommentFormHidden() {
    var captchaBlock = document.getElementById('smi-captcha');
    return captchaBlock && captchaBlock.style.display == 'none' ? true : false;
}

function showCommentForm() {
    if (isCommentFormHidden()) {
        document.getElementById('smi-captcha').style.display = 'block';
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = '/zf/index/js';
        document.getElementById('commentformdiv').appendChild(script);
    }
}

function insertSmile(smileName) {
    var textElem = document.getElementById('comment');
    if (!textElem) {
        return;
    }
    textElem.focus();
    var sb = textElem.value.substr(textElem.value.length - 1, 1);
    textElem.value += ((sb != ' ' && sb != "\n") ? ' ' : '') + smileName;
    return false;
}

function commentDelete(id) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = '/zf/index/moderatecomment/command/delete/id/' + id;
    document.getElementById('comment-' + id).appendChild(script);
}

function commentSpam(id) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = '/zf/index/moderatecomment/command/spam/id/' + id;
    document.getElementById('comment-' + id).appendChild(script);
}

function sendComplaint(id) {
    document.getElementById('complaint_' + id).style.backgroundImage = 'url("/zf/public/images/ajax_indicator.gif")';
    var iframe = document.getElementById('iframe');
    if (iframe) {
         iframe.src = '/zf/index/complaint/id/' + id;
    }
}

RegExp.escape = function(text) {
    if (!arguments.callee.sRE) {
      var specials = [
        '/', '.', '*', '+', '?', '|',
        '(', ')', '[', ']', '{', '}', '\\'
      ];
      arguments.callee.sRE = new RegExp(
        '(\\' + specials.join('|\\') + ')', 'g'
      );
    }
    return text.replace(arguments.callee.sRE, '\\$1');
};

var chat = {
    status: 0,
    title: '',
    title1: 'Сообщение!',
    title2: '**************',
    timeout: 500,
    timer: 0,

    blink: function() {
        if (this.status != 0) {
            if (document.title == this.title1) {
                document.title = this.title2;
            } else {
                document.title = this.title1;
            }
            setTimeout('chat.blink()', this.timeout);
        } else {
            document.title = this.title;
        }
    },

    notify: function(status) {
        if (this.status == status) {
            return;
        }
        this.status = status;
        if (this.status != 0) {
            this.title = document.title;
            this.timer = setTimeout('chat.blink()', this.timeout);
        }
    }
};

/**
 * скрипт просмотрщика
 */
function loadXMLDoc(handler) {
	var req = null;
	var reqTimeout;
	
    if (window.XMLHttpRequest) {
        try {
            req = new XMLHttpRequest();
        } catch (e){}
    } else if (window.ActiveXObject) {
        try {
            req = new ActiveXObject('Msxml2.XMLHTTP');
        } catch (e){
            try {
                req = new ActiveXObject('Microsoft.XMLHTTP');
            } catch (e){}
        }
    }

    if (req) {
    	req.onreadystatechange = processReqChange;
    }
    
    this.load = function(url) {
        url = url.replace(/&amp;/g, '&');
	    if (req) {
	        req.open("GET", url, true);
	        req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
	        req.send(null);
	        reqTimeout = setTimeout("req.abort();", 5000);
	    } else {
	        //alert("Браузер не поддерживает AJAX");
	    }
    };

	function processReqChange() {
	    if (req.readyState == 4) {
	        clearTimeout(reqTimeout);
	        if (req.status == 200) {
	        	if (handler) {
	        		handler(req.responseText);
	        	}
	        } else {
	            //alert("Не удалось получить данные:\n" + req.statusText);
	        }
	    }
	}
}

function processViewer(responseText) {
    if (responseText != '') document.getElementById("viewer").innerHTML = responseText;

    if (document.getElementById("arrconfirm")){
        eval(unescape(document.getElementById("arrconfirm").innerHTML));
        document.getElementById("arrconfirm").innerHTML = '';
    }
}

function is_array(input){
    return typeof(input)=='object'&&(input instanceof Array);
}


function Get_Cookie( name ) {
    var start = document.cookie.indexOf( name + "=" );
    var len = start + name.length + 1;
    if ( ( !start ) &&
    ( name != document.cookie.substring( 0, name.length ) ) )
    {
    return null;
    }
    if ( start == -1 ) return null;
    var end = document.cookie.indexOf( ";", len );
    if ( end == -1 ) end = document.cookie.length;
    return document.cookie.substring( len, end );
}

function requestdata(idnews) {

    var mail = new Array();
    var mail = document.cookie.match(/comment_author_email_[^=]+=*?/g);

    var value_mail = mail ? getCookie(mail[0]) : '';

    if (location.href.indexOf('test') > 0) {
        alert(document.cookie + '===' + mail + '===' + value_mail);
    }
    
    var ajax = new loadXMLDoc(processViewer);

    if (value_mail) {
        var mail = mail[0].match(/=(.*)/);
        var nick = new Array();
        var nick = document.cookie.match(/comment_author_[^=]+=*?/g);
        var value_nick = Get_Cookie(nick[0]);
        ajax.load('/ajax/viewer.php?mail=' + value_mail + '&nick=' + value_nick + '&new=' + idnews);
    } else {
        if (document.cookie.indexOf('MG_guest') < 0) {
            var exdate = new Date();
            var curdate = exdate.getMinutes();
            exdate.setMinutes(exdate.getMinutes() + 1);
            document.cookie = "MG_guest=true; expires=" + exdate.toGMTString() + "; path=/news/" + idnews;
            ajax.load('/ajax/viewer.php?' + 'new=' + idnews);
        } else {
        	ajax.load('/ajax/viewer.php?mg_guest=true' + '&new=' + idnews);
        }
    }
}

function uploadPopUp(type, formelementid) {
    tburl = '/zf/index/upload/type/' + type;
    newwindow = window.open(tburl,'tinybrowser','height=200,width=600,scrollbars=yes,resizable=yes');
    if (window.focus) {
        newwindow.focus();
    }
    return false;
 }

function insertImage(path) {
    quoteInsert(null, '<img src="' + path + '" alt="" />');
}

function validateCommentForm() {
    var form = document.getElementById('commentform');
    if (form.author.value == '') {
        alert('Укажите имя!');
        form.author.focus();
        return false;
    }
    if (form.email.value == '') {
        alert('Укажите E-mail!');
        form.email.focus();
        return false;
    }
    if (form.comment.value == '') {
        alert('Введите комментарий!');
        form.comment.focus();
        return false;
    }
    var captcha = document.getElementById('captcha');
    if (captcha && captcha.value == '') {
        showCommentForm();
        alert('Введите текст, изображенный на картинке');
        captcha.focus();
        return false;
    }
    return true;
}

function loadCommentChildren(commentId) {
	var ajax = new loadXMLDoc(processChildren);
	var divChildren = document.getElementById('comment-' + commentId + '-children');
	if (divChildren && divChildren.innerHTML != '') {
		return;
	}
	divChildren.innerHTML = '<img src="/zf/public/images/loading.gif" width="16" height="16" alt="Загрузка..."/>';
	ajax.load('/zf/index/comment-ajax/id/' + commentId);
	
	function processChildren(response) {
		if (divChildren) {
			divChildren.innerHTML = response;
		}
	}
}
