var isCSS, isW3C, isIE4, isNN4, isIE6CSS, isOpera;
var communityLinkCounter = 0;
    
function MarkAll(mark)
{
  var objects = document.getElementsByName('ids[]');

  if (objects != null)
     for (i = 0; i < objects.length; i++)
         objects[i].checked = mark;
}

function mark_all_by_name(name, mark)
{
    var objects = document.getElementsByName(name);
    if (objects != null)
    {
        for (var i=0; i<objects.length; i++)
        {
            if (objects[i].tagName.toUpperCase() == 'INPUT' && objects[i].type == "checkbox")
            {
                objects[i].checked = mark;
            }
        }
    }
}

function mark_all_by_attr(attr, mark)
{
    var cbx = document.getElementsByTagName("INPUT");
    for (var i=0; i<cbx.length; i++)
    {
        if (cbx[i].type == "checkbox" && cbx[i].getAttribute(attr) == '1')
        {
            cbx[i].checked = mark;
        }
    }
}

function join_values_by_name(name)
{
    var objects = document.getElementsByName(name);
    var resArray = new Array();
    if (objects != null)
    {
        for (var i=0; i<objects.length; i++)
        {
            if (objects[i].tagName.toUpperCase() == 'INPUT' && objects[i].type == "checkbox" && objects[i].checked)
            {
                resArray.push(objects[i].value);
            }
        }
    }
    return resArray.join("~");
}

function create_bookmark()
{
	var title = document.title;
	var url = location.href;

	if (window.sidebar)
		window.sidebar.addPanel(title, url, "");
	else if(window.opera && window.print)
	{ 
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	} 
	else if(document.all)
	{
		window.external.AddFavorite(url, title);
	}
	else
	{
		//alert("Попробуйте добавить в избранное вручную :-)");
	}
	return false;
}

function addUniverRow()
{
	var row = document.getElementById('edu_new_row');
	document.getElementById('edu_add_rows').innerHTML += row.innerHTML;
}

function addOrgRow()
{
	var row = document.getElementById('org_new_row');
	document.getElementById('org_add_rows').innerHTML += row.innerHTML;
}

function set_smile(code)
{
	var frm = document.getElementById('smiles_anchor').form;
	if (frm)
	{
		frm.getElementsByTagName('textarea')[0].value = frm.getElementsByTagName('textarea')[0].value + code;
	}
}
var newWindow;
function PopupWindow(URL,w,h) 
{
	self.name="smmain"
	var topPos=0;
	var leftPos= 0;

	/*if (!h)
	{
		var winHeight=screen.availHeight-50;
	} else {
		var winHeight = h;
	}
        */
	var center = window.center();
    topPos = center.y - parseInt(h/2);
    leftPos = center.x - parseInt(w/2);

	if (!newWindow || newWindow.closed) 
	{
		newWindow = window.open(URL, "details", "dependent=yes,top="+topPos+",left="+leftPos+",height="+h+",width="+w+",status=no,toolbar=no,menubar=no,location=no,resizable=yes,scrollbars=yes");
	} else
	{newWindow.document.location.href = URL;
		newWindow.focus();
	}

}//

var imwin;
function userFileBrowser (field_name, url, type, win) 
{
	imwin = win;

    var cmsURL = "/web/imagemanager_user/images.php?js=mcImageManager.insertFileToTinyMCE_clear&remember=true"
    var searchString = window.location.search;  // possible parameters
      
    // block multiple file browser windows
   
        tinyMCE.openWindow({
            file : cmsURL +"&type=" + type,
            title : "Хранилище изображений",
            width : 700,
            height : 500,
            close_previous : "no"
        }, {
            window : win,
            input : field_name,
            resizable : "yes",
            inline : "yes",
            editor_id : tinyMCE.selectedInstance.editorId
        });
    

    return false;
}


function validateCommunityLinkForm(elem)
{
    if (!elem) return false;
    var res = true;

    var ta = elem.getElementsByTagName("TEXTAREA")[0];
    if (!ta.value) res = false;
    
    var sels = elem.getElementsByTagName("SELECT");
    for (var i=0; i<sels.length; i++)
    {
        if (!sels[i].value) res = false;
    }
    if (!res)
    {
        alert('Необходимо заполнить все поля');
    }
    return res;
}

function replaceCommunityLinkForm(elem)
{
    if (!elem) return;
    
    var ta = elem.getElementsByTagName("TEXTAREA")[0];
    var cb = elem.getElementsByTagName("INPUT")[0];
    ta.value = "";
    ta.name = "comment[" + communityLinkCounter +"]";
    ta.id = "comment_" + communityLinkCounter;
    cb.checked = false;
    cb.name = "show_first[" + communityLinkCounter + "]";
    
    var sels = elem.getElementsByTagName("SELECT");
    for (var i=0; i<sels.length; i++)
    {
        sels[i].value = 0;
        var name = sels[i].name.replace("[]", "");
        sels[i].name = name + "[" + communityLinkCounter + "]";
    }
    communityLinkCounter++;
    
    
 
}

function lookupCommunityLinkForm(elem)
{
    if (!elem) return null;
    while (elem.parentNode)
    {
        if (elem.parentNode.tagName.toLowerCase() == "table" && elem.parentNode.getAttribute("is_community_form") == '1')
        {
            return elem.parentNode;
        }
        else
        {
            elem = elem.parentNode;
        }
    }
    return null;
}

function lookupCommunityTarget(elem)
{
    while (elem.parentNode)
    {
        if (elem.parentNode.tagName.toLowerCase() == "table")
        {
            var sels = elem.parentNode.getElementsByTagName('SELECT');
            for (var i=0; i<sels.length; i++)
            {
                if (sels[i].getAttribute('is_community_chooser') == '1')
                {
                    return sels[i];
                }
            }
            elem = elem.parentNode;
        }
        else
        {
            elem = elem.parentNode;
        }
    }
    return null;
}

function cloneFragment(source, dest, validator, replacer)
{
    if (!source)
    {
        return;
    }
    
    if (validator == null || validator(source))
    {
        var fragment = document.getElementById(source.getAttribute('etalon')).cloneNode(true);
        fragment.id = "frm_"+communityLinkCounter;
        fragment.style['display'] = "";
        replacer(fragment);
        dest.appendChild(fragment);
        
        window.setTimeout("appendMCE("+communityLinkCounter+")",500);
    }
}

function cloneTableRow(source, dest, replacer)
{
    if (!source)
    {
        return;
    }
    var new_row = dest.insertRow(dest.rows.length);
    for (var i=0; i<source.cells.length; i++)
    {
        var cell = new_row.insertCell(new_row.cells.length);
        cell.innerHTML = source.cells[i].innerHTML;
        cell.style['paddingLeft'] = source.cells[i].style['paddingLeft'];
        cell.style['paddingRight'] = source.cells[i].style['paddingRight'];
        cell.style['paddingTop'] = source.cells[i].style['paddingTop'];
        cell.style['paddingBottom'] = source.cells[i].style['paddingBottom'];
        cell.style['verticalAlign'] = source.cells[i].style['verticalAlign'];
    }
    replacer(new_row);
}

var LastSpec = -1;

function rewriteSpecRow(elem)
{
    LastSpec--;
   var inp = elem.getElementsByTagName("INPUT")[0];
   inp.name = "email["+LastSpec+"]";
   
   var sel = elem.getElementsByTagName("SELECT")[0];
   sel.name = "catalog["+LastSpec+"]";
   
   return elem;
}

function appendMCE(num)
{
	num -=1;
	if (document.getElementById('comment_'+num))
    	{
    		//tinyMCE.execCommand('mceRemoveControl', true, 'comment_'+num);
    		tinyMCE.execCommand('mceAddControl', true, 'comment_'+num);
    	} 
}
function buildSelectOptions(elem, opts)
{
    if (!elem) return;
    
    while (elem.options.length)
    {
        elem.remove(0);
    }
    
    for (var i=0; i<opts.length; i++)
    {
        var opt = new Option();
        opt.text = opts[i].text;
        opt.value = opts[i].value;
        elem.options.add(opt);
    }
}

function cloneFragmentSimple(source,dest)
{

    if (!source)
    {
        return;
    }
     var fragment = source.cloneNode(true);
     fragment.style['display'] = "";
     //replacer(fragment);
     dest.style['display'] = "";
     dest.appendChild(fragment);
          
}

var posx;
var posy ;


function moveElementToCursor(id)
{
	alert(posy);
	alert(posx)
	if (document.getElementById(id))
	{
		document.getElementById(id).style.left = posx +'px';
		document.getElementById(id).style.top = (posy-55) + 'px';
	}

}//

function detectMouseCoordinates(ev){
	ev   = ev || window.event;
	if(ev.pageX || ev.pageY){
		posx = ev.pageX;
		posy = ev.pageY
	} else
	{
		posx = ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		posy = ev.clientY + document.body.scrollTop  - document.body.clientTop
	}

}


function setGaleryImage(img)
{
    if (!img) return;
    document.getElementById('image_container').getElementsByTagName('IMG')[0].src = img.src;
    document.getElementById('stored_avatar').value = img.getAttribute('filename');
}

function initMaxlengthCountdown(id)
{
    if (!document.getElementById(id) || !document.getElementById(id+"_countdown"))
    {
        return;
    }
    document.getElementById(id).onkeyup = function (event)
    {
        if (this.getAttribute("maxlength") - this.value.length < 0)
        {
            this.value = this.value.substr(0, this.getAttribute('maxlength'));
        }
        document.getElementById(this.id+"_countdown").innerHTML = "Осталось: "+(this.getAttribute("maxlength") - this.value.length)+" символов";
    }
}

function initAllCountdowns()
{
    var inputs = document.getElementsByTagName('INPUT');
    for (var i=0; i<inputs.length; i++)
    {
        if (inputs[i].getAttribute("is_countdown") == 1)
        {
            initMaxlengthCountdown(inputs[i].id);
        }
    }
    var areas = document.getElementsByTagName('TREXTAREA');
    for (var i=0; i<areas.length; i++)
    {
        if (areas[i].getAttribute("is_countdown") == 1)
        {
            initMaxlengthCountdown(areas[i].id);
        }
    }
}

function toogleEditorMode(el,sEditorID) {
	try {
		if(!el.checked) {
			tinyMCE.execCommand('mceRemoveControl', true, sEditorID);
		} else {
			tinyMCE.execCommand('mceAddControl', true, sEditorID);

		}
	} catch(e) {
		//error handling
	}
}


function doBuy(id)
{
    if (id)
    {
        if (document.getElementById('num_'+id))
        {
            var num = $('#num_'+id).val();
        } else
        {
            num = 1;
        }
        $.post('/eapteka/add_to_cart',{id:id,num:num},function (res)
                {
                    var resArr = res.split('~');
                    if (resArr[0]>0 && resArr[1]>0)
                    {
                        $('#tsum_all').show();
                        $('#num_products_in_cart').html(resArr[0]);
                        $('#total_cart_sum').html(resArr[1]);
                        $('#after_buy_title').html(resArr[2]);
                        $('#after_buy_description').html(resArr[3]);
                        $('#word_products').html(getWordEnding($('#num_products_in_cart').html(),'товар','товара','товаров'));
                        $('#after_buy_alert').dialog('open');

                    }
                }
                
            );

                
        /*
        if (document.getElementById('num_'+id))
        {
            window.location.assign('/eapteka/buy/'+id+'?num='+document.getElementById('num_'+id).value);
        } else
        {
            window.location.assign('/eapteka/buy/'+id+'?num=1');
        }
        */
    }

    return false;
}


window.size = function()
{
	var w = 0;
	var h = 0;

	//IE
	if(!window.innerWidth)
	{
		//strict mode
		if(!(document.documentElement.clientWidth == 0))
		{
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		}
		//quirks mode
		else
		{
			w = document.body.clientWidth;
			h = document.body.clientHeight;
		}
	}
	//w3c
	else
	{
		w = window.innerWidth;
		h = window.innerHeight;
	}
	return {width:w,height:h};
}

window.center = function()
{
	var hWnd = (arguments[0] != null) ? arguments[0] : {width:0,height:0};

	var _x = 0;
	var _y = 0;
	var offsetX = 0;
	var offsetY = 0;

	//IE
	if(!window.pageYOffset)
	{
		//strict mode
		if(!(document.documentElement.scrollTop == 0))
		{
			offsetY = document.documentElement.scrollTop;
			offsetX = document.documentElement.scrollLeft;
		}
		//quirks mode
		else
		{
			offsetY = document.body.scrollTop;
			offsetX = document.body.scrollLeft;
		}
	}
	//w3c
	else
	{
		offsetX = window.pageXOffset;
		offsetY = window.pageYOffset;
	}

	_x = ((this.size().width-hWnd.width)/2)+offsetX;
	_y = ((this.size().height-hWnd.height)/2)+offsetY;

	return{x:_x,y:_y};
}

function addCts(from_id,to_id, callback)
{
    this.index = -1;
    if (document.getElementById(from_id) && document.getElementById(to_id))
    {
       //var cts = document.getElementById(from_id).innerHTML;
       var cts = $('#'+from_id).html();
       if (callback != null)
       {
            cts = callback(cts);
       }
       var a = Ext.DomHelper.insertHtml('beforeEnd',document.getElementById(to_id),cts);
    }
}

var multiplier_index = -1;
var popup_multiplier_index = -1;
function replace_test_result_block(text)
{
       text = text.replace("result[0]", "result["+multiplier_index+"]");
       text = text.replace("result_title[0]", "result_title["+multiplier_index+"]");
       text = text.replace("score_min[0]", "score_min["+multiplier_index+"]");
       text = text.replace("score_max[0]", "score_max["+multiplier_index+"]");
       text = text.replace("result_image[0]", "result_image["+multiplier_index+"]");
       multiplier_index--;
       return text;
}

function replace_test_answer_block(text)
{
       var answer_index = 0;
       $('table[is_answer=1]').find("input[rel=answ]").each(function(){
            if (parseInt(this.value) > answer_index)
            {
                answer_index = parseInt(this.value);
            }
       });
       answer_index++;
       text = text.replace("priority[0]", "priority["+popup_multiplier_index+"]");
       text = text.replace("score[0]", "score["+popup_multiplier_index+"]");
       text = text.replace("answer[0]", "answer["+popup_multiplier_index+"]");
       text = text.replace("correct[0]", "correct["+popup_multiplier_index+"]");
       text = text.replace("image[0]", "image["+popup_multiplier_index+"]");
       text = text.replace(/value="?0"?/, 'value="'+answer_index+'"');
       popup_multiplier_index--;
       return text;
}

function replace_poll_block(text)
{
    var answer_index = 0;
    $('table[is_answer=1]').find("input").each(function(){
        if (parseInt(this.value) > answer_index)
        {
            answer_index = parseInt(this.value);
        }
    });
    answer_index++;
    text = text.replace(/value="?0"?/, 'value="'+answer_index+'"');
    return text;
}

function replace_test_block(text)
{
    var answer_index = 0;
    $('table[is_question=1]').find("input[is_priority=1]").each(function(){
        if (parseInt(this.value) > answer_index)
        {
            answer_index = parseInt(this.value);
        }
    });
    answer_index++;
    //alert(answer_index);
    text = text.replace(/value="?0"?/, 'value="'+answer_index+'"');
    return text;
}



var active_cm_id = null;
function initRatingUI(cm_id)
{
    active_cm_id = cm_id;

    $.blockUI({
                message: $('#rating_dialog'),
                css: {width: '400px',padding: '10px'}
            });
}

function fillRatingUI(cm_id)
{
    $('#d_cm_title').html($('#cm_title_'+cm_id).html());
    $('#d_cm_community').html($('#cm_community_'+cm_id).html());
    $('#d_cm_rating').val($('#cm_rating_'+cm_id).val());
    $('#d_cm_comment').val($('#cm_comment_'+cm_id).html());
}


function closeRatingUI()
{
  $.unblockUI({message: $('#rating_dialog')});
  active_cm_id = null;
}

function updateCmComment()
{
    data= new Object();
    data['comment'] = $('#d_cm_comment').val();
    data['rating'] = $('#d_cm_rating').val();
    data['comment_id'] = active_cm_id;
    data['method'] = 'update_cm_comment';
    data['plain'] = 1;

    $.unblockUI({message: $('#rating_dialog')});
    $.blockUI({message: $('#ajax_dialog')});

    $.post('/ajax/call', data, function(ret)
    {
        $.unblockUI({message: $('#ajax_dialog')});

        if (ret == -1)
        {
            alert('Для того, чтобы оставить отзыв, необходимо авторизоваться');
            return;
        }

        if (ret == 1)
        {
            $('#cm_rating_'+active_cm_id).val($('#d_cm_rating').val());
            $('#cm_rating_name_'+active_cm_id).html($('#d_cm_rating option:selected').text());
            $('#cm_comment_'+active_cm_id).html($('#d_cm_comment').val());

            $.growlUI('Ваш отзыв обновлен');

        } else
        {
            alert("Отзыв не сохранен, пожалуйста сообщите администрации сайта об этом")

        }

       active_cm_id = null;

    });


}
function saveRatingCM(community_id, rate)
{
    data= new Object();
    data['comment'] = $('#rating_comment').val();
    if (typeof rate != 'undefined')
    {
        data['rating'] = rate;
    } else
    {
        data['rating'] = $('#rate_'+active_cm_id).val();
    }
    
    data['cm_id'] = active_cm_id;
    data['community_id'] = community_id;
    data['method'] = 'post_cm_rate';
    data['plain'] = 1;

    $.unblockUI({message: $('#rating_dialog')});    
    $.blockUI({message: $('#ajax_dialog')});

    $.post('/ajax/call', data, function(ret_data)
    {
        var retArr = ret_data.split('~');
        var ret = retArr[0];
        var newRating = retArr[1];
        var newComments = retArr[2];
        
        $.unblockUI({message: $('#ajax_dialog')});

        if (ret == -1)
        {
            alert('Для того, чтобы оставить отзыв, необходимо авторизоваться');
            return;
        }
        
        if (ret == 0 || ret == 1)
        {
            $('#cm_num_comments_'+active_cm_id).html(newComments);
            $('#cm_num_comments_'+active_cm_id+'_'+community_id).html(newComments);
            $('#cm_rating_'+active_cm_id+'_'+community_id).html(newRating);
            if (document.getElementById('cm_rating_'+active_cm_id))
            {
                $('#cm_rating_'+active_cm_id).html(newRating);
            } else
            {
                if (document.getElementById('cm_rating_cont_'+active_cm_id))
                {
                    $('#cm_rating_cont_'+active_cm_id).html('<span id="cm_rating_'+active_cm_id+'">'+newRating+'</span>%<br /> случаев');
                }
            }

        }
        if (ret == 0)
        {
            $.growlUI('Спасибо', 'Ваш отзыв сохранен!');

        } else if (ret == 1)
        {
            $.growlUI('Ваш отзыв сохранен', 'Вы уже оставляли отзыв на это лекарство. Старый отзыв удален из системы');

        } else
        {
            alert("Отзыв не сохранен, пожалуйста сообщите администрации сайта об этом")

        }

       active_cm_id = null;
        
    });

    
    $('#rating_comment').val('');

    
}

function contest_block()
{
    $.blockUI({
				message: $('#contest_block'),
                css: {width: '400px',padding: '10px', top: '30%'}
            });
}

function contest_block_close()
{
	$.unblockUI();
}

function contest_block2()
{
    $.blockUI({
                message: $('#contest_block2'),
                css: {width: '400px',padding: '10px', top: '30%'}
            });
}

function append_contest_vote(id, vote, callback_func)
{
    var res = ajaxSyncCall('contest_vote', {id: id, vote: vote})
    var resArr = eval(res).split(':');
    $('#total_score').html(resArr[0]);
    $('#total_voters').html(resArr[1]);
    $('#vote_section').html('<strong>Спасибо, Ваш голос учтен</strong>');
    if (typeof callback_func == 'function')
    {
        callback_func();
    }
}

function append_lesson_vote(id, vote, callback_func)
{
    var res = ajaxSyncCall('vote', {id: id, vote: vote, service: "lesson"})
    $('#total_score').html(eval(res));
    $('#vote_section').html('<strong>Спасибо, Ваш голос учтен</strong>');
    if (typeof callback_func == 'function')
    {
        callback_func();
    }
}


function append_poll_vote(id)
{
    var votes = [];
    $('#POLL_CONTAINER').find("input").each(function(){
        if (this.type == "checkbox" || this.type == "radio")
        {
            if (this.checked)
            {
                votes.push(this.value);
            }
        }
    });
    var res = ajaxSyncCall('poll_vote', {id: id, votes: votes.join("~"), plain: 1});
    $('#POLL_CONTAINER').html(res);
}

function set_back_url(back_url)
{
    $('#back_url').val(back_url);
}

function submitTestHandler()
{
    var questions = [];
    var priority = [];
    $('span[is_question]').each(function(){
        questions.push(this.getAttribute('is_question'));
        priority.push(this.getAttribute('priority'));
    });
    for (var i=0; i<questions.length; i++)
    {
        if ($("input[type=radio][question_id="+questions[i]+"][checked]").size() <= 0)
        {
            var warn = false;
            $("input[type=radio][question_id="+questions[i]+"]").each(function(){
                if (!warn)
                {
                    alert("Вы не ответили на вопрос "+priority[i]+"!");
                    warn = true;
                }
            });
            return false;
        }
    }
    return true;
}

function submitQuizHandler()
{
    var questions = [];
    var priority = [];
    var types = [];
    $('span[is_question]').each(function(){
        questions.push(this.getAttribute('is_question'));
        priority.push(this.getAttribute('priority'));
        types.push(this.getAttribute('question_type'));
    });
    for (var i=0; i<questions.length; i++)
    {
        switch (types[i])
        {
            case '1':
                if ($("input[type=radio][question_id="+questions[i]+"][checked]").size() <= 0)
                {
                    alert("Вы не ответили на вопрос "+priority[i]+"!");
                    return false;
                }
            break;
            case '2':
            case '3':
                if ($("input[type=checkbox][question_id="+questions[i]+"][checked]").size() <= 0)
                {
                    alert("Вы не ответили на вопрос "+priority[i]+"!");
                    return false;
                }
            break;
            case '4':
                var answers = [];
                var warn = false;
                $("select[question_id="+questions[i]+"]").each(function(){
                    if ($.inArray(this.value, answers) >= 0)
                    {
                        warn = true;
                    }
                    else
                    {
                        answers.push(this.value);
                    }
                });
                if (warn)
                {
                    alert("Для ответа на вопрос " + priority[i] + " необходимо расположить ответы в правильной последовательности без повторений");
                    return false;
                }
            break;
        }
    }
    return true;
}

function bulkRemoveComments()
{
    var list = $("input[type=checkbox][is_comment_hdl=1][checked]");
    if (list.size() <= 0)
    {
        alert("Ничего не выбрано");
        return;
    }
    if (!confirm("Удалить выбранные комментарии ?"))
    {
        return;
    }
    var comments = [];
    list.each(function(){
        comments.push(this.value);
    });
    location.href="/community/delete_comments/"+comments.join("~");
}


// Flash Player Version Detection - Rev 1.6
// Detect Client Browser type
// Copyright(c) 2005-2006 Adobe Macromedia Software, LLC. All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");

			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful.

			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}

	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;

	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			} else if (versionRevision[0] == "b") {
				versionRevision = versionRevision.substring(1);
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera)
        {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function checkLoginSubmitData()
{
    $.post("/login/login_popup", $('#inner_login').serializeArray(),
        function(data)
        {
            if (data == '1' || data == '2')
            {
                //$('#inner_login')[0].submit();
                //window.location.reload();
                var loc = window.location.href;
                if (loc.indexOf('#') != -1)
                {
                    loc = loc.substr(0, loc.indexOf('#'));
                }
                if (loc.indexOf('?') != -1)
                {
                    loc += "&open_comment=1";
                }
                else
                {
                    loc += "?open_comment=1";
                }
                if (data == '2')
                {
                    loc += '#opinion_form';
                }
                window.location.href = loc;
            } else
            {
                alert(data);
            }
        });

     return false;

}


function getWordEnding(num,var1,var2,var3)
	{
        
        num = parseInt(num);
		if (num>=10 && num <20)
        {
            return var3;
        }
		num = ''+num;
        
		var intt = parseInt(num.substr(-1,1));

		switch (intt) {
			case 1:
				return var1;
				break;


			case 2:
			case 3:
			case 4:

				return var2;

				break;


			default:
				return var3;
				break;
        }
    }//