//////////////////////////////////////////////////////////////////////////////////////////////
//                                      JavaScript Functions                                      //                                            ver. 2.0                                          //                                        Author: Alex Kvak                                      //////////////////////////////////////////////////////////////////////////////////////////////

// initializing a browser
var aks_isIE=0,aks_isNN=0, aks_isMF=0;
if (navigator.userAgent.indexOf("Firefox")!=-1) aks_isMF=1;
if    (document.all) 
    aks_isIE=1;
else 
    if(document.layers) 
        aks_isNN=1;
var aks_isOpera = (navigator.userAgent.indexOf("Opera") > 0);
//////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////
/*
    Sets active OPTION in SELECT element
    @param tag_id     id of the SELECT element
    @param value     value of OPTION element to be selected
*/
//////////////////////////////////////////////////////////////////////////////////////////
function aks_set_select_value(tag_id,value)
{
    if (!(obj = my$(tag_id))) return false;
    var lo_len = obj.options.length;
    var lo = obj.options;

    for(i=lo_len-1;i>=0;i--)
        if (lo[i].value == value)
        {
            lo[i].selected = true;
            break;
        }
    return true;
}
//////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////
function aks_suredelete(obj)
{
    val_ = confirm(suredelete_confirm);
    if (val_== false) return false;
    obj.action_.value='delete';
    return true;
}
//////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////
function aks_suredelete_rubrik(obj)
{
    return confirm(suredelete2_confirm);
}
//////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////
function aks_sureoben(obj)
{
    val_ = confirm(sureoben_confirm);
    if (val_== false) return false;
    obj.action_.value='oben';
    return true;
}
//////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////
function aks_sureunten(obj)
{
    val_ = confirm(sureunten_confirm);
    if (val_== false) return false;
    obj.action_.value='unten';
    return true;
}
//////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////
// return Element by Id 
function aks_getElement(n)
{
   if (typeof document.getElementById(n) != "undefined")
       return document.getElementById(n);
   else
          return false;
}
//////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////
// return Element by Id 
function my$(n)
{
   if (typeof document.getElementById(n) != "undefined")
       return document.getElementById(n);
   else
          return false;
}
//////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////
// creates a popUp
function aks_popupWnd(url,title,width,height,scrollbars)
{
   if (title == "random")
        title = "wnd"+(Math.random() * 10).toString();
     
   var options = "status=off,menubar=off,height="+height+",width="+width;
   var xtop = (screen.height-height)/2-15, xleft = (screen.width-width)/2;
   options += ",top="+xtop+",left="+xleft;
   
   if ( (scrollbars == "on") || (scrollbars == true) )
       options += ",scrollbars";
   else
       if (scrollbars == "auto")
        options += ",scrollbars=auto";
    else
           options += ",scrollbars=off";
   
   var popup = window.open(url,title,options); 
   popup.document.close();
}
//////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////
// changes the CheckBox flag of Element num
function aks_changeCheck(num)
{
    if (obj = aks_getElement(num))
        obj.checked = !obj.checked;
}
//////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////
// set the display property of Element num
function aks_setView(num, show)
{
    var obj = aks_getElement(num);
    obj.style.display = (show) ? 'block':'none';
}
//////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////
// set the visibility of Element num    
function aks_setVisibility(num, show)
{
    var obj = aks_getElement(num);
    obj.style.visibility = (show) ? "visible":"hidden";
}
//////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////
// returns the display property of Element num            
function aks_getView(num)
{
    var obj = aks_getElement(num);
    return obj.style.display;
}
//////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////
// changes the visibility ogf Element num        
function aks_changeView(num)
{
    visibility_ = aks_getView(num);
    show = (visibility_ == 'none') ? true : false;
    aks_setView(num, show);
    return true;
}
//////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////
// sets the color farbe to all cells of table row obj
function aks_setFarbe(obj,farbe)
{
    theCells = obj.cells;
    var rowCellsCnt = theCells.length;
    for (c = 0; c < rowCellsCnt; c++) 
        theCells[c].style.backgroundColor=farbe;
}
//////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////
// sets the color farbe to specified cell obj
function aks_setFarbeCell(obj,farbe)
{
     obj.style.backgroundColor = farbe;
}
//////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////
// sets the color farbe to specified cell obj
function aks_goToURL(url)
{
     location.href = url;
}
//////////////////////////////////////////////////////////////////////////////////////////

/* CROSS-BROWSER EVENT HANDLER */
function addEvent(obj, evType, fn){
     if (obj.attachEvent){
         var r = obj.attachEvent("on"+evType, fn);
        return r;
     } else if (obj.addEventListener){
         obj.addEventListener(evType, fn, true);
         return true;
     } else {
        return false;
     }
}

// check for an empty field 
function aks_checkSuche(field,value)
{
    return ((aks_getElement(field).value!='') && (aks_getElement(field).value!=value));
}

////////////////////////
function setAllCheckBoxes(prefix) {
    var inputs = document.getElementsByTagName("INPUT");
    var re = /.*/;
    if (typeof prefix != "undefined") 
        re = new RegExp("^"+prefix);
    for(var i=0;i<inputs.length;i++) {
        if ((inputs[i].type == "checkbox") && inputs[i].id.match(re) ) 
            inputs[i].checked = true;
    }
}
////////////////////////

function setCheckedCheckBoxes() {
    var inputs = document.getElementsByTagName("INPUT");
    for(var i=0;i<inputs.length;i++) {
        if (inputs[i].type == "checkbox") {
            inputs[i].checked = (inputs[i].getAttributeNode('checked')!=null && 
                (inputs[i].getAttributeNode('checked').value=='true' || 
                    inputs[i].getAttributeNode('checked').value==''));
//            alert(inputs[i].getAttributeNode('checked').value);
        }
    }
}

////////////////////////
function clearAllCheckBoxes() {
    var inputs = document.getElementsByTagName("INPUT");
    for(var i=0;i<inputs.length;i++) {
        if (inputs[i].type == "checkbox") 
            inputs[i].checked = false;
    }
}
////////////////////////

////////////////////////
function checkCheckBoxes() {
    var inputs = document.getElementsByTagName("INPUT");
    for(var i=0;i<inputs.length;i++) {
        if ( (inputs[i].type == "checkbox") 
            && inputs[i].checked) return true;
    }
    return false;
}
////////////////////////

function PasteInTexArea(id,str) {
    myTxt = my$(id);
    if (document.selection) {
        myTxt.focus();
        sel = document.selection.createRange();
        sel.text = str;
    }
    //MOZILLA/NETSCAPE support
    else if (myTxt.selectionStart || myTxt.selectionStart == "0") {
        var startPos = myTxt.selectionStart;
        var endPos = myTxt.selectionEnd;
        var chaineSql = myTxt.value;

        myTxt.value = chaineSql.substring(0, startPos) + str + chaineSql.substring(endPos, chaineSql.length);
    } else {
        myTxt.value += str;
    }
}

function showKalendar(name_) {
    aks_popupWnd("/modules/kalender/kalender.php?"+
        "feld="+name_,"kalenderPopUp",210,195,false);
}

function sendForm(formID,reqFields,callback) {
    var dataForAjax = new Object();

//    alert('#'+formID+' :input');
//    return;
    
    var err = '';
    $.each($('#'+formID+' :input'),function(){ 
        $(this).attr("disabled","disabled"); 
        if ($(this).attr("name")) {
            eval('dataForAjax.'+$(this).attr("name")+" = \""+encodeURIComponent($(this).attr("value"))+"\";");
//            alert($(this).attr("name") + ' ' + $(this).attr("value"));
            if ( ($.inArray( $(this).attr("name"), reqFields)!=-1) &&  ($(this).attr("value") == '') )
                err += "Заполните поле '"+findLabel($(this).attr("id"))+"'\n";
        }
    } );
    
//    alert(err); return;
    
    if (err) {
        alert(err);
        $.each($('#'+formID+' :input'),function(){ $(this).attr("disabled","") } ); 
    } else {
        
            
        $.ajax({
                type: "POST",
                url: '/ajax.php?action=sendForm', 
                dataType : 'text',
                data: dataForAjax,
                success: function(response) {
                    if (callback) callback();
                    $.each($('#'+formID+' :input'),function(){
                        $(this).attr("disabled","");
                        if ($(this).attr("id") && ($(this).attr("type")!='submit')) $(this).attr("value",'');
                    } );
                    if (response) alert(response);
                    else alert('Сообщение отправлено');
                }
        });
    }
}

function findLabel(elemID) {
    var foundLabel = '';
     $.each($('label'),function(){ 
        if ($(this).attr("for") == elemID)
            foundLabel = $(this).html().replace(/:$/,''); 
     } );
     return foundLabel;
}

function setCookie2 (name, value, expireseconds, path, domain, secure) {
      var exdate = new Date();
      if (expireseconds) exdate.setDate(exdate.getDate()+expireseconds);
       
      document.cookie = name + "=" + escape(value) +
        ((expireseconds) ? "; expires=" + exdate.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function r(id) {
    my$(id).src=my$(id).src+'&'+Math.random();
}

function addToCart(gID) {
    addfields = '';
    $("select[name^='addfield']").each(function() {
        addfields += '&' + $(this).attr('name') + '=' + $(this).val();
    });
    
    $().jOverlay({url: '/cart_small.htm?put='+gID + addfields, imgLoading : '/img/ajax-loader.gif', autoHide : false, bgClickToClose : false, success : function () { $('#cart_brief').load('cart_small.htm?getcontents') } });
}


function postComment(goodID) {
    if ($('#commentName').attr("value") == '' || $('#commentText').attr("value") == '') return;
    
    $.each($(':input'),function(){ 
        $(this).attr("disabled","disabled");
    });

     $.ajax({
       type: "GET",
       url: "ajax?action=addComment&name="+encodeURIComponent($('#commentName').attr("value"))+"&msg="+encodeURIComponent($('#commentText').attr("value"))+"&email="+encodeURIComponent($('#commentEmail').attr("value"))+"&subscribe="+encodeURIComponent($('#commentSubscribe').attr("checked"))+'&g='+goodID,
       data: '',
       success: function(msg){
//        $('#TRaddComment').hide();
        $('#infDiv').fadeIn("slow");
        $.each($(':input'),function(){ 
            $(this).attr("disabled","");
        });
        my$('commentName').value = my$('commentText').value = my$('commentEmail').value = ''; 
        my$('commentSubscribe').checked = false;
        setTimeout(function(){$('#infDiv').fadeOut("slow")}, 5000);
        
        loadComments(goodID);
       },
       error: function(obj,msg){
        alert(msg);
       }
     });
}

function postReply(goodID, comment_id) {
    if ($('#replyFormName'+comment_id).attr("value") == '' || $('#replyFormText'+comment_id).attr("value") == '') return;
    
    $.each($(':input'),function(){ 
        $(this).attr("disabled","disabled");
    });

     $.ajax({
       type: "GET",
       url: "ajax?action=addReply&name="+encodeURIComponent($('#replyFormName'+comment_id).attr("value"))+"&msg="+encodeURIComponent($('#replyFormText'+comment_id).attr("value"))+'&g='+goodID+'&p='+comment_id,
       data: '',
       success: function(msg){
        $('#replyForm'+comment_id).detach()
       
        $('#infDiv').fadeIn("slow");
        $.each($(':input'),function(){ 
            $(this).attr("disabled","");
        });
        $('#replyFormName'+comment_id).attr("value",'');
        $('#replyFormText'+comment_id).attr("value",'');
        setTimeout(function(){$('#infDiv').fadeOut("slow")}, 5000);
        
        
        loadComments(goodID);
       },
       error: function(obj,msg){
        alert(msg);
       }
     });
}

function loadComments(goodID) {
    $.get("ajax?action=getComments&g="+goodID,
        function(data){
            $('#comments').html(data);
    });
}

function showReplyForm(goodID, obj, comment_id) {
    if ( (form = $('#replyForm'+comment_id)).length ) {
        form.detach()
    } else {
        form = $('#replyForm').clone(1).appendTo($(obj.parentNode));
        form.attr('id', 'replyForm'+comment_id);
        $('#replyForm'+comment_id+' .replyFormName').attr('id', 'replyFormName'+comment_id);
        $('#replyForm'+comment_id+' .replyFormText').attr('id', 'replyFormText'+comment_id);
        $('#replyForm'+comment_id+' .replyFormBtn').bind('click', function() { postReply(goodID, comment_id) } );
        form.show();
    }
}
