var pageRequest = 'parts/Do_request.php';

var nchamber = {};

var allQueryParams =
{
    all: (document.location + '').toQueryParams(),
    getParameter: function(param)
    {
        for(var key in this.all)
        {
            if (key == param && !Object.isUndefined(this.all[key])) return this.all[key];
        }
        return false;
    },
    isParameter: function(param)
    {
        return !!this.getParameter(param);
    }
};

function getPageName()
{
    return location.pathname.substring(location.pathname.lastIndexOf('/') + 1);
}

function getQueryParams(params)
{
    var query = '';
    for(var param in params)
    {
        query += (query?'&':'?')+param+'='+params[param];
    }
    return query;
}

/*
 *
 * @param contentType 10,20 or 30
 * @param xid and id of tcontent
 * @param cri contentReferenceId is con_submenu_ref from tcontent
 * @param pageId the id of the page
 * @param parsed should content be parsed with Content_parser
 */
var iframeEditor;
function editContent(contentType, xid, pageId, parsed)
{
    iframeEditor = document.createElement('iframe');
    iframeEditor.className = 'window-content-editor';
    iframeEditor.scrolling = "no";
    iframeEditor.style.width = window.siteVariables.cms_width + 'px';
    iframeEditor.style.height = window.siteVariables.cms_height + 'px';
    var windowSizes = getCrossSizes();
    //alert(windowSizes.height+', '+scriptParams.cms_height+', '+calculateMiddle(windowSizes.height, scriptParams.cms_height));
    iframeEditor.style.top = calculateMiddle(windowSizes.height, window.siteVariables.cms_height) + 'px';
    iframeEditor.style.left = calculateMiddle(windowSizes.width, window.siteVariables.cms_width) + 'px';
    var params = {
        'contentType': contentType,
        'xid': xid,
        'pageId': pageId,
        'parsed': parsed
    };
    if (parsed == '0') params['tiny'] = 'true';
    iframeEditor.src = 'editor.php'+getQueryParams(params);
    top.document.body.appendChild(iframeEditor);
}

function isLogged(func)
{
    new Ajax.Request(pageRequest,
    {
        parameters:
        {
            action: 'isLogged'
        },
        onSuccess: function(request)
        {
            //            alert(request.responseText);
            if (request.responseText == '-1')
            {
                redirect('about');
            }
            else if (request.responseText == '1')
            {
                func();
            }
        },
        onFailure: function(request){
            alert('Something went wrong...'+'\n'+request.responseText)
            }
    });
}

function alertArguments()
{
    alert($A(arguments));
}

function calculateMiddle(fullSize, partSize)
{
    return (fullSize - partSize) / 2;
}

function doContent(content)
{
    var params = {
        action: getAction() + 'Content'
        ,
        id: allQueryParams.getParameter('xid')
        ,
        xcontent: getCurrentContent()
        ,
        pageId: allQueryParams.getParameter('pageId')
        ,
        contentType: allQueryParams.getParameter('contentType')
        ,
        parsed: allQueryParams.getParameter('parsed')
        ,
        lang: top.window.siteVariables.lang
    }
    //    alert(Object.values(params));
    new Ajax.Request(pageRequest,
    {
        parameters: params,
        onSuccess: function(request)
        {
            //            alert(request.responseText);
            switch (request.responseText)
            {
                case '-1': //not-logged
                    toggleEditor();
                    focusOnField('username');
                    break;
                case '-2': //xml syntax error
                    alert('Xml syntax error!');
                    break;
                default:
                    reloadTop();
                    break;
            }
        },
        onFailure: function(request){
            alert('Something went wrong...'+'\n'+request.responseText)
            }
    });
}

function focusOnField(id)
{
    $(id).focus();
}

function getCurrentContent()
{
    if (window.tinyMCE) {
        tinyMCE.triggerSave(true,true);
    }
    var content = $('contentEdit').value;
    return content;
}

function toggleEditor()
{
    $('editor').toggle();
    $('editor-login').toggle();
}

function getAction()
{
    var contentId = allQueryParams.getParameter('xid');
    if (contentId != 0 && $('contentEdit').value) return 'update';
    if (contentId != 0 && !$('contentEdit').value) return 'delete';
    return 'insert';
}

function cancelEditor()
{
    reloadTop();
}

function reloadTop()
{
    top.location = top.location + '';
}

function setLang(lang)
{
    top.location = getPageName() + getQueryParams({
        'lang': lang
    });
}

function setVariables(obj)
{
    window.siteVariables = obj;
}

function getScriptParams(param)
{
    var bodyTag = document.getElementsByTagName('head')[0];
    var scriptTag = bodyTag.getElementsByTagName('script');
    var ncc = /ncc.js/;
    var params;
    for (var i = 0; i < scriptTag.length; i++)
    {
        if (scriptTag[i].src.match(ncc))
        {
            params = scriptTag[i].src.substr(scriptTag[i].src.indexOf('?')+1);
            params = params.split(';');
            var allParams = {};
            var splitedParams;
            for (var j = 0; j < params.length; j++)
            {
                splitedParams = params[j].split('=');
                allParams[splitedParams[0]] = splitedParams[1];
            }
        }
    }
    if (!Object.isUndefined(param)) return allParams[param];
    return allParams;
}

function sessionWarning(msg, time)
{
    setTimeout(function(){
        alert(msg);
    }, time*(1000*60));
}

function doFlags()
{
    var flags = $$('.flag');
    flags.each(function(flag){
        if (flag.id != window.siteVariables.lang){
            flag.addClassName('non-active-lang');
        }
    });
}
/**
 * A function to create black-transparent-curtain to block page behind,
 * and to show iframe-modal-popup, on top of curtain, for user to log in
 */
function loginPopup(){
    var cur = document.createElement('iframe');
    cur.id = 'curtain';
    var data = getCrossSizes();
    var wdth = data['width'], hght = data['height'], scrl = data['scrollY'], fltr = data['filter'];
    //    alert(wdth+' : '+hght);
    cur.style.cssText = fltr+' width: '+wdth+'px; height: '+(hght+scrl)+'px; position: absolute; top: 0; left: 0; '+
    'z-index: 888; background-color: black;';
    var ifr = document.createElement('iframe');
    ifr.id = 'editadmin';
    var iwdth = 400;
    var ihght = 150;
    var topp = (hght-ihght)/2;
    var leftp = (wdth-iwdth)/2;
    ifr.style.cssText = 'width: '+iwdth+'px; height: '+ihght+'px; z-index: 999; position: absolute; top: '+topp+'px; left: '+leftp+'px;'+
    'background-color: white;';
    ifr.src = 'login_popup.php';
    document.body.appendChild(cur);
    document.body.appendChild(ifr);
    $$('html, body').invoke('addClassName', 'no-scroll');
}

/**
 * Calculate cross-browser (not only) page sizes
 * @return Object with width, height, how much is scrolled and a filter (the amount of transparency for curatain)
 */
function getCrossSizes(base)
{
    var width, height, scrollY, filter;
    if(Prototype.Browser.IE){
        if (Object.isUndefined(base)) base = document.body;
        else base = base.document.body;
        width = base.clientWidth;
        height = base.clientHeight;
        scrollY = base.scrollTop;
        filter = 'filter:alpha(opacity=50);';
    }
    else{
        if (Object.isUndefined(base)) base = window;
        else base = base.window;
        width = base.innerWidth;
        height = base.innerHeight;
        scrollY = base.pageYOffset;
        filter = 'opacity:0.5;';
    }
    return {
        'width': width,
        'height': height,
        'scrollY': scrollY,
        'filter': filter
    };
}

function removeCurtain()
{
    parent.document.body.removeChild(parent.document.getElementById("curtain"));
    parent.document.body.removeChild(parent.document.getElementById("editadmin"));
    $$('html, body').invoke('removeClassName', 'no-scroll');
}

function buttonHover()
{
    $('editor-header-close').observe('mouseover', function(){
        this.addClassName('editor-header-close-h');
    });
    $('editor-header-close').observe('mouseout', function(){
        this.removeClassName('editor-header-close-h');
    });
    
    if (!$('editor-header-save')) return;
    $('editor-header-save').observe('mouseover', function(){
        this.addClassName('editor-header-save-hover');
    });
    $('editor-header-save').observe('mouseout', function(){
        this.removeClassName('editor-header-save-hover');
    });
}


//var instanceOfNicEditor;
//function createNic()
//{
//    instanceOfNicEditor = new nicEditor({
//        fullPanel : true,
//        onSave : function(content, id, instance){
//            doContent(content);
//        }
//    }).panelInstance('contentEdit');
//}

nchamber.tiny = {
    init: function(){
        if (Object.isUndefined(tinyMCE)) {
            return;
        }
        tinyMCE.init({
            // General options
            document_base_url : "../../../../",
            mode : "textareas",
            theme : "advanced",
            plugins : "safari,table,advhr,advimage,advlink,advlist,contextmenu,inlinepopups,insertdatetime,media,paste,preview,"+
            "searchreplace,print,paste,visualchars,xhtmlxtras",

            // Theme options
            theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect",
            theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,"+
            "|,undo,redo,|,link,unlink,anchor,image,cleanup,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
            theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,visualchars,media,advhr,|,print,|,pastetext,pasteword,selectall",
            theme_advanced_buttons4 : "cite,abbr,acronym,del,ins",
            theme_advanced_toolbar_location : "top",
            theme_advanced_toolbar_align : "left",
            theme_advanced_statusbar_location : "bottom",
            theme_advanced_resizing : true,
            paste_auto_cleanup_on_paste : true,
            plugin_preview_width : "560"
        });
    }
}

function setEditorSize()
{
    var header = 30;
    var editorWidth = top.window.siteVariables.cms_width;
    var offset = allQueryParams.isParameter('tiny') ? 65 : 0;
    var editorHeight = top.window.siteVariables.cms_height - 5 - header + offset;
    $('contentEdit').style.width = editorWidth + 'px';
    $('contentEdit').style.height = editorHeight + 'px';
    $('editor-login').style.height = editorHeight + 'px';
}

function doLogin()
{
    new Ajax.Request(pageRequest,
    {
        parameters:
        {
            action: 'doLogin'
            ,
            username: $('username').value
            ,
            password: $('password').value
        },
        onSuccess: function(request)
        {
            //            alert(request.responseText);
            if (request.responseText == '-1')
            {
                $$('.login-error')[0].style.visibility = 'visible';
            }
            else
            {
                if ($('editor'))
                {
                    toggleEditor();
                }
                else
                {
                    redirect('about');
                }
            }
        },
        onFailure: function(request){
            alert('Something went wrong...'+'\n'+request.responseText)
            }
    });
}

function addExtraQueryParam(locationObject, param)
{
    if (locationObject.search)
    {
        if (locationObject.search.indexOf(param) != -1)
        {
            return '';
        }
        return '&'+param;
    }
    return '?'+param;
}

function doLogout()
{
    new Ajax.Request(pageRequest,
    {
        parameters:
        {
            action: 'doLogout'
        },
        onSuccess: function(request)
        {
            //            alert(request.responseText);
            redirect(getPageName());
        },
        onFailure: function(request){
            alert('Something went wrong...'+'\n'+request.responseText)
            }
    });
}

function doUpdateNameAndPassword()
{
    var params = {
        action: 'doUpdateNameAndPassword',
        old_name: $('old-username').value,
        new_name: $('new-username').value,
        old_pass: $('old-password').value,
        new_pass: $('new-password').value
    };
    //    alert(Object.values(params));
    new Ajax.Request(pageRequest,
    {
        parameters: params,
        onSuccess: function(request)
        {
            //            alert(request.responseText);
            if (request.responseText == '-1')
            {
                $$('.update-message-0')[0].style.display = 'block';
            }
            else if (request.responseText == '1')
            {
                $$('.update-message-1')[0].style.display = 'block';
            //                doLogout();
            }
        },
        onFailure: function(request){
            alert('Something went wrong...'+'\n'+request.responseText)
            }
    });
}

/**
 * This function sets menu hover, menu active item and correct header photo
 */
function setFewThings()
{
    var pgName = getPageName()?getPageName():'netherlands-chamber-commerce-slovakia';
    var headerClassnames = ['header-b', 'header-c', 'header-a'];
    var i = 0;
    var mod = 3;
    var notMenuPage = true;
    $$('.menu-item').each(function(menuItem){
        var link = menuItem.childElements()[1].childElements()[0];
        if (link.href.substring(link.href.lastIndexOf('/')+1) == pgName)
        {
            notMenuPage = false;
            //set active menu background color
            menuItem.childElements()[0].style.backgroundColor = '#b42b23';
            menuItem.childElements()[0].style.opacity = '0.5';
            menuItem.childElements()[0].style.filter = 'alpha(opacity=50)';
            menuItem.childElements()[1].style.backgroundColor = '#b42b23';
            link.style.color = 'white';
            //set header pic
            $('header').addClassName(headerClassnames[i%mod]);
        }
        link.observe('mouseover', function(){
            menuItem.childElements()[0].addClassName('menu-red-top');
            menuItem.childElements()[1].addClassName('menu-red-text');
            link.addClassName('link-color');
        });
        link.observe('mouseout', function(){
            menuItem.childElements()[0].removeClassName('menu-red-top');
            menuItem.childElements()[1].removeClassName('menu-red-text');
            link.removeClassName('link-color');
        });
        i++;
    });
    //set default header image if page is not in menu (login, loginupdate and upload)
    if (notMenuPage) $('header').addClassName(headerClassnames[0]);
}

function redirect(path)
{
    top.location = path;
}

function deleteContent(contentId)
{
    if (!contentId) return;
    var deleteIt = confirm('Content from this page will be permanently deleted from database. Continue?');
    if (!deleteIt) return;
    new Ajax.Request(pageRequest,
    {
        parameters:
        {
            action: 'deleteContent',
            id: contentId
        },
        onSuccess: function(request)
        {
            //            alert(request.responseText);
            reloadTop();
        },
        onFailure: function(request){
            alert('Something went wrong...'+'\n'+request.responseText)
            }
    });
}

var uploadFunc;
function observeSubmit(id)
{
    uploadFunc = function(){
        uploadFile(id)
        };
    $$('.submit-button')[0].observe('click', uploadFunc);
}

function uploadFile(id)
{
    if (!$(id).value) return;
    if ($('upload-message').visible()) $('upload-message').toggle();
    $$('.upload-wait')[0].toggle();
    $$('.submit-button')[0].addClassName('diabled');
    $$('.submit-button')[0].stopObserving('click', uploadFunc);
    $('upload-form').submit();
}

function openFullNewsText(clickedElement)
{
    var eventTextElement = $(clickedElement).nextSiblings()[0];
    eventTextElement.toggle();
    if (!Object.isUndefined(window.eventClickedElement) && window.eventClickedElement != eventTextElement
        && window.eventClickedElement.visible())
        {
        //close previous opened event
        window.eventClickedElement.toggle();
    }
    window.eventClickedElement = eventTextElement;
}

function jumplink(pagePart)
{
    try {
        $$('.'+pagePart)[0].scrollIntoView();
    } catch (exception) {}
}

function enableLogoCheckbox(resizeCheckBox)
{
    if (resizeCheckBox.checked)
    {
        $('upload-checkbox-logo').disabled = false;
        $('upload-holder-logo').removeClassName('upload-holder-logo');
    }
    else
    {
        $('upload-checkbox-logo').disabled = true;
        $('upload-holder-logo').addClassName('upload-holder-logo');
    }
}

function readMore(readMoreLink)
{
    var toHide = readMoreLink.tagName.toLowerCase()=='a'?readMoreLink.parentNode:readMoreLink;
    var toShow = toHide.previousSibling;
    toHide.style.display = 'none';
    toShow.style.display = 'inline';
}

function toggleGallery(galleryLink)
{
    var gallery = $(galleryLink).nextSiblings()[0];
    gallery.toggle();
}

function formatBulletins(){
    $$('.con-bulletin').each(function(bulletin, index){
        bulletin.addClassName('bulletin-row');
        var mod = index % 4;
        // omit only first one
        if (mod == 0 && index != 0) {
            bulletin.setStyle({
                clear:'both'
            });
        }
    });
}

function fixThumbs(){
    var allHolders = $$('.event-image-holder');
    var mod, isLast, allImages;
    allHolders.each(function(holder){
        allImages = holder.childElements();
        allImages.each(function(image, index){
            mod = index % 4;
            isLast = allImages.length  - 1 == index;
            // insert clear element to make nice 4 column gallery
            if (mod == 3 || isLast) {
                image.insert({
                    after: new Element('div', {
                        'className': 'clear-float'
                    })
                });
            }
        });
    });
}