//adres hosta z django wraz z ewentualnym kontekstem;
HOST_ADDRESS="http://localhost:8000";

function showStartOfPage() {
    // Top of page if no # mark in address
    window.location.href='#';
}

function destroyWidget(widget) {
    console.log("destroyWidget(" + widget + ")");
    if (widget) {
        widget.destroyRecursive();
    }
}

function toggleDivDisplay(divId) {
	var div = document.getElementById(divId);
	if (div !== null) {
		if (div.style.display == 'none') {
			div.style.display = 'block';
		} else {
			div.style.display = 'none';
		}
	}
}


function loadHtmlIntoDialog(htmlURL, dlg) {
    console.log("loadHtmlIntoDialog(" +
        htmlURL + ", " + dlg.id + ")");
	
    dojo.xhrPost({
        url: htmlURL,
		handleAs:"text",
        load: function(response, ioArgs) {
            console.log("load from " + htmlURL + " into " + dlg.id);
            dlg.destroyDescendants();
            dlg.setContent(response);
            dlg.show();
            return response;
        },
        error: function(response, ioArgs) {
            console.log("error from " + htmlURL + " into " + dlg.id);
            dlg.destroyDescendants();
            dlg.setContent(response);
            dlg.show();
            return response;
        }
    });
}


function assert(/*Boolean*/ booleanValue, /*String?*/ message){
    // summary: 
    //          Throws an exception if the assertion fails.
    // description: 
    //          If the asserted condition is true, this method does nothing. If the;
    //          condition is false, we throw an error with a error message. 
    // booleanValue: Must be true for the assertion to succeed.
    // message: A string describing the assertion.
    // throws: Throws an Error if 'booleanValue' is false.
    if(!booleanValue){
        if(!message){
            message = "An assert statement failed.\n" +
            "The method assert() was called with a 'false' value.\n";
        }
        throw new Error(message);
    }
}

dojo.registerModulePath("7bulls_ext","/static/7bulls_ext");

dojo.require("dijit.Dialog");
dojo.require("dijit.Menu");
dojo.require("dijit.Tree");
dojo.require("dijit.form.Button");
dojo.require("dijit.form.CheckBox");
dojo.require("dijit.form.DateTextBox");
dojo.require("dijit.form.DropDownButton");
dojo.require("dijit.form.FilteringSelect");
dojo.require("dijit.form.Form");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.layout.TabContainer");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dojo.parser");
dojo.require("dijit.form.NumberTextBox");


//tabela na przechowywanie podpiec do dialogBoxa
loginWindowListeners = [];


function cleanLoginWindowListeners(){
	//czysci poprzednie listenery
	for ( var i in loginWindowListeners )
	{
		dojo.disconnect(loginWindowListeners[i]);
	} 
}

function loginWhen401(response, ioArgs, callFunc){

    console.log("loginWhen401()");
	statusCode = ioArgs.xhr.status;
    
    var browserName = null;
    if (statusCode == 401){
        console.log("statusCode == 401");
    	browserName=navigator.appName; 
    	if (browserName=="Microsoft Internet Explorer"){
    		alert("Funkcjonalność niedostępna, proszę się zalogować");
    		return;
    	}
    	cleanLoginWindowListeners();
        loadHtmlIntoDialog("/profile/loginUserFormDialog", dijit.byId("loginDialog"));
        
        //przypiszmy do przycisku ok probe zalogowania 
        loginWindowListeners[loginWindowListeners.length] = dojo.connect(dijit.byId("loginDialog"), 'execute', function(content){ 
        console.log('loginWhen401: trying to log in....');
        console.log('loginWhen401: trying to obtain login...');
        email = dijit.byId('dialogEmail').getValue();
        console.log('loginWhen401: login grabbed successful');
        console.log('loginWhen401: trying to obtain password...');
        password = dijit.byId('dialogPassword').getValue();
        console.log('loginWhen401: password grabbed successful');
        loginArgs = {'email':email, 'password':password};
        dojo.xhrPost({
                url: '/profile/loginUser',
        		content: loginArgs,
                load: function(response, ioArgs) {
                    console.log("loginWhen401: user logged in.");
                    console.log("loginWhen401: refreshing menu");
                    loadHtmlIntoDiv("/profile/upperMenu", dijit.byId("menuAreaLevel2"));
                    console.log("loginWhen401: loading original call");
                    callFunc();
                    return response;
                },
                error: function(response, ioArgs) {
                	alert("Logowanie nie powiodło się. Spróbuj jeszcze raz");
                	dijit.byId("loginDialog").show();
                }
        	});
        });
    }
    else if (statusCode == 403) {
       
        console.log("statusCode == 403");
    	browserName=navigator.appName; 
    	if (browserName=="Microsoft Internet Explorer"){
    		alert("Funkcjonalność dostępna jedynie dla klientów. Proszę zalogować się na konto posiadające odpowiednią rolę.");
    		return;
    	}
    	cleanLoginWindowListeners();
        loadHtmlIntoDialog("/profile/loginUserFormDialog403", dijit.byId("loginDialog"));
        
        //przypiszmy do przycisku ok probe zalogowania 
        loginWindowListeners[loginWindowListeners.length] = dojo.connect(dijit.byId("loginDialog"), 'execute', function(content){ 
        console.log('loginWhen403: trying to log in....');
        console.log('loginWhen403: trying to obtain login...');
        email = dijit.byId('dialogEmail').getValue();
        console.log('loginWhen403: login grabbed successful');
        console.log('loginWhen403: trying to obtain password...');
        password = dijit.byId('dialogPassword').getValue();
        console.log('loginWhen403: password grabbed successful');
        loginArgs = {'email':email, 'password':password};
        dojo.xhrPost({
                url: '/profile/loginUser',
        		content: loginArgs,
                load: function(response, ioArgs) {
                    console.log("loginWhen403: user logged in.");
                    console.log("loginWhen403: refreshing menu");
                    loadHtmlIntoDiv("/profile/upperMenu", dijit.byId("menuAreaLevel2"));
                    console.log("loginWhen403: loading original call");
                    callFunc();
                    return response;
                },
                error: function(response, ioArgs) {
                	alert("Logowanie nie powiodło się. Spróbuj jeszcze raz");
                	dijit.byId("loginDialog").show();
                }
        	});
        });
    
    }
    else {
    }
}

function loadHtmlWithArgs(htmlURL, args, func) {
    console.log("loadHtmlWithArgs(" + htmlURL + ")");
    //console.dir(args)

    dojo.xhrPost({
        url: htmlURL,
		content: args,
        load: function(response, ioArgs) {
            console.log("load from " + htmlURL);
            func(response);
            return response;
        },
        error: function(response, ioArgs) {
            console.log("error from " + htmlURL);
            loginWhen401(response, ioArgs, function(){loadHtmlWithArgs(htmlURL, args, func);});
            return response;
        }
    });
}

function loadHtml(htmlURL, func) {
    console.log("loadHtml(" + htmlURL + ")");

    dojo.xhrPost({
        url: htmlURL,
        load: function(response, ioArgs) {
            console.log("load from " + htmlURL);
            func(response);
            return response;
        },
        error: function(response, ioArgs) {
        	console.log("error from " + htmlURL);
            loginWhen401(response, ioArgs, function(){loadHtml(htmlURL, func);});
            return response;
        }
    });
}

function loadHtmlWithForm(htmlURL, formName, func) {
    console.log("loadHtmlIntoDivWithForm(" + htmlURL + ", " + formName + ")");

    dojo.xhrPost({
        url: htmlURL,
        form: formName,
        load: function(response, ioArgs) {
            console.log("load from " + htmlURL);
            func(response);
            return response;
        },
        error: function(response, ioArgs) {
            console.log("error from " + htmlURL);
            loginWhen401(response, ioArgs, function(){loadHtmlWithForm(htmlURL, formName, func);});
            return response;
        }
    });
}

function loadHtmlIntoDiv(htmlURL, divObj) {
    console.log("loadHtmlIntoDiv(" + htmlURL + ", " + divObj.id + ")");
    
    widget = dijit.byId(divObj.id);
    if (widget) {
        // It's a dijit wiget, we will use setHref();
        console.log("setHref(" + htmlURL + ")");
        widget.destroyDescendants();
        widget.setHref(htmlURL);
        return;
    }
    dojo.xhrGet({
        url: htmlURL,
        divObj: divObj,
        load: function(response, ioArgs) {
            console.log("load from " + htmlURL + " into " + this.divObj);
            this.divObj.innerHTML = response;
            dojo.parser.parse(this.divObj);
            return response;
        },
        error: function(response, ioArgs) {
            console.log("error from " + htmlURL + " into " + this.divObj);
            // alert(response);
            return response;
        }
    });
}

function loadHtmlIntoDivHandleErrors(htmlURL, divObj, onSuccess, onFailure) {
    console.log("loadHtmlIntoDivHandleErrors(" + htmlURL + ", " + divObj.id + ")");
    
    widget = dijit.byId(divObj.id);
    if (widget) {
        // It's a dijit wiget, we will use setHref();
        console.log("setHref(" + htmlURL + ")");
        widget.destroyDescendants();
        widget.setHref(htmlURL);
        return;
    }
    dojo.xhrGet({
        url: htmlURL,
        divObj: divObj,
        load: function(response, ioArgs) {
            console.log("load from " + htmlURL + " into " + this.divObj);
            this.divObj.innerHTML = response;
            dojo.parser.parse(this.divObj);
            if (onSuccess) {
            	onSuccess();
            }
            return response;
        },
        error: function(response, ioArgs) {
            console.log("error from " + htmlURL + " into " + this.divObj);
            // alert(response);
            if (onFailure) {
            	onFailure();
            }
            return response;
        }
    });
}

function loadHtmlIntoDivWithForm(htmlURL, divObj, formName) {
    console.log("loadHtmlIntoDivWithForm(" +
        htmlURL + ", " + divObj + "," + formName + ")");

    assert(document.forms[formName], "Missing form: " + formName);

    dojo.xhrGet({
        url: htmlURL,
        divObj: divObj,
        form: formName,
        load: function(response, ioArgs) {
            console.log("load from " + htmlURL + " into " + this.divObj);

            widget = dijit.byId(divObj.id);
            if (widget) {
                // It's a dijit wiget, we will use setHref();
                console.log("setHref(" + htmlURL + ")");
                widget.destroyDescendants();
                widget.setContent(response);
                return;
            }
            else {
                this.divObj.innerHTML = response;
                dojo.parser.parse(this.divObj);
            }

            return response;
        },
        error: function(response, ioArgs) {
            console.log("error from " + htmlURL + " into " + this.divObj);
            // alert(response);
            return response;
        }
    });
}

function loadHtmlIntoContentDivWithForm(htmlURL, divName, formName) {
    console.log("loadHtmlIntoContentDivWithForm(" +
        htmlURL + ", " + divName + "," + formName + ")");
	widget = dijit.byId(divName);
	divObj = dojo.byId(divName);

	divObj.style.cursor = 'wait';

    dojo.xhrPost({
        url: htmlURL,
		handleAs:"text",
        form: formName,
        load: function(response, ioArgs) {
            console.log("load from " + htmlURL + " into " + divName);
            widget.setContent(response);
            divObj.style.cursor = 'default';
            showStartOfPage();
            return response;
        },
        error: function(response, ioArgs) {
            divObj.style.cursor = 'default';
            console.log("error from " + htmlURL + " into " + divName);
            // alert(response);
            return response;
        }
    });
}
function loadHtmlIntoContentDiv(htmlURL, divName) {
    console.log("loadHtmlIntoContentDiv(" +
        htmlURL + ", " + divName + ")");
    divObj = dijit.byId(divName);
    if (!divObj) {
        alert("Missing ContentDiv: " + divName);
        return;
    }

    dojo.xhrGet({
        url: htmlURL,
        divObj: divObj,
        load: function(response, ioArgs) {
            console.log("load from " + htmlURL + " into " + this.divObj);
            this.divObj.setContent(response);
            return response;
        },
        error: function(response, ioArgs) {
        	console.log("error from " + htmlURL);
        	loginWhen401(response, ioArgs, function(){loadHtmlIntoContentDiv(htmlURL, divName);});
            return response;
        }
    });
}
function loadHtmlIntoContentDivWithContent(htmlURL, divName, content) {
    console.log("loadHtmlIntoContentDivWithContent(" +
        htmlURL + ", " + divName + ")");
    divObj = dijit.byId(divName);
    dojo.xhrPost({
        url: htmlURL,
        divObj: divObj,
		content: content,
        load: function(response, ioArgs) {
            console.log("load from " + htmlURL + " into " + this.divObj);
            this.divObj.setContent(response);
            showStartOfPage();
            return response;
        },
        error: function(response, ioArgs) {
            console.log("error from " + htmlURL + " into " + this.divObj);
            // alert(response);
            return response;
        }
    });
}


function prond_highlight(self) {
    self.className = 'highlight';
}

function prond_unhighlight(self) {
    self.className = "";
}

// [DCI013];
function edit_order(orderID) {
//	  loadHtmlIntoDialog("/mgmt/order/" + orderID,dijit.byId("orderDetailDialog"));
    loadHtmlIntoDiv("/mgmt/order/" + orderID, document.getElementById("Content"));
//    window.location = "/mgmt/order/" + orderID;
}

function changeOrderRead(box, orderID){
	if (box.checked){
		value = 1;
	}
	else{
		value = "";
	}
	loadHtml("/mgmt/order/changeOrderRead/"+orderID+"/"+value,
        function (resp) {
            dojo.byId('order_filter').submit();  
        });
}



function show_my_orders(div) {
    div.style.display = "block";
}

function showOrderDetailsPending(orderID) {
    window.location = "/profile/order/pending/" + orderID;
}

function showOrderDetailsArchive(orderID) {
    window.location = "/profile/order/archive/" + orderID;
}

function showOrderDetailsNormal(orderID) {
    window.location = "/profile/order/" + orderID;
}

function view_order(orderID) {
    window.open("/mgmt/view_order/" + orderID, "_blank");
}

function view_invoice(orderID) {
    window.open("/mgmt/view_invoice/" + orderID, "_blank");
}

function send_invoice(orderID) {
	loadHtml("/mgmt/send_invoice/" + orderID,
        function (resp) {
            if (resp == 'OK') {
                alert('Wysłano');
				window.location.reload();
            }
            else {
                alert('Wystąpił błąd');
            }
        });
}

function viewItem(itemID) {
    loadHtmlIntoDiv(
        "/mgmt/order/item/" + itemID,
        document.getElementById("edit_ordersForm_itemParts"));
}

function toBookStore()
{
	window.location.href="/shop/product/all";
}





function changeVisibility(box, divId)
{

	console.log("changeVisibility(" + box.getValue() + "," + divId + ")");
	var elm = document.getElementById(divId);
	elm.style.display = (box.value ? "none":"block");

}

function boxChangeVisibility(box, divId)
{
	var elm = document.getElementById(divId);
	elm.style.display = (box.checked ? "":"none");
}

function orderListFilterSearchAction() {
    dateStart = document.getElementById("order_filter_dateStart");
    dateEnd = document.getElementById("order_filter_dateEnd");
    if (dateEnd.value && dateStart.value > dateEnd.value) {
        alert("Data początkowa powinna być wcześniejsza od daty końcowej.");
        return false;
    }
    document.getElementById('order_filter').submit();
}

function orderListFilterResetAction() {
    document.getElementById("order_filter_searchText").value = "";
    document.getElementById("order_filter_readChbox").checked = false;
    document.getElementById("order_filter_testChbox").checked = false;
    document.getElementById("order_filter_status").value = "";
    document.getElementById("order_filter_invoice").value = "";
    document.getElementById("order_filter_paymentMethod").value = "";
    document.getElementById("order_filter_deliveryMethod").value = "";
    document.getElementById("dateType").checked = false;
    document.getElementById("order_filter_dateType_place").checked = true;
    document.getElementById("order_filter_dateType_payment").checked = false;
    document.getElementById("order_filter_dateType_realisation").checked = false;
    document.getElementById("order_filter_dateStart").value = "";
    document.getElementById("order_filter_dateEnd").value = "";
    document.getElementById('order_filter').submit();
}

function generateOrderReport() {
    dateStart = document.getElementById("reportDateStart");
    dateEnd = document.getElementById("reportDateEnd");
    if (dateEnd.value===null || dateEnd.value==="" || dateStart.value ===null || dateStart.value==="") {
        alert("Data poczatkowa i końcowa muszą być wypełnione");
        return false;
    }
    if (dateEnd.value && dateStart.value > dateEnd.value) {
        alert("Data poczatkowa nie powinna być po dacie koncowej");
        return false;
    }
    document.getElementById('order_report').submit();
}

function showOrderList(page_id) {
    window.location = "/mgmt/orders?page="+page_id;
}

function setCheckboxesState(value, checkboxName) {
    console.log("setCheckboxesState(value=" + value + ")");
    dojo.forEach(dojo.query('*[name="' + checkboxName + '"]'), function (obj) {
        console.log("obj.id=" + obj.id);
        widget = dijit.byId(obj.id);
        console.log(widget);
        widget.setValue(value);
    });
}

function setChildCheckboxesState(value, checkboxName, childrenIds) {
	ids = childrenIds.split(",");
	for (ch in ids) {
		id = checkboxName + ids[ch].replace(/^\s\s*/, '').replace(/\s\s*$/, '');
		dojo.forEach(dojo.query('*[id="' + id + '"]'), function (obj) {
			widget = dijit.byId(obj.id);
   			widget.setValue(value);
    	});
    }
}


function init_tinyMCE_once(div_ids) {
    tinyMCE.init({
        mode : "none",
        theme : "advanced",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_buttons1 : "fullscreen,separator,preview,separator,bold,italic,underline,strikethrough,separator,bullist,numlist,outdent,indent,separator,undo,redo,separator,link,unlink,anchor,separator,image,cleanup,help,separator,code",
        theme_advanced_buttons2 : "",
        theme_advanced_buttons3 : "",
        auto_cleanup_word : true,
        plugins : "table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,zoom,flash,searchreplace,print,contextmenu,fullscreen",
        plugin_insertdate_dateFormat : "%m/%d/%Y",
        plugin_insertdate_timeFormat : "%H:%M:%S",
        extended_valid_elements : "a[name|href|target=_blank|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
        fullscreen_settings : {
            theme_advanced_path_location : "top",
            theme_advanced_buttons1 : "fullscreen,separator,preview,separator,cut,copy,paste,separator,undo,redo,separator,search,replace,separator,code,separator,cleanup,separator,bold,italic,underline,strikethrough,separator,forecolor,backcolor,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,help",
            theme_advanced_buttons2 : "removeformat,styleselect,formatselect,fontselect,fontsizeselect,separator,bullist,numlist,outdent,indent,separator,link,unlink,anchor",
            theme_advanced_buttons3 : "sub,sup,separator,image,insertdate,inserttime,separator,tablecontrols,separator,hr,advhr,visualaid,separator,charmap,emotions,iespell,flash,separator,print"
        }
    });
    tinyMCE.execCommand("mceAddControl", false, div_ids);
}

function addOptionToCombo(combo, optionValue, optionText) {
    var sel = document.createElement('option');
    sel.text = optionText;
    sel.value = optionValue;
    try {
        elSel.add(sel, null); // standard
    } catch (Ex) {
        elSel.add(sel); // IE only
    }
}

function show_promotionDetails(promotionID) {
    loadHtmlIntoDialog("/promo/promotion/" + promotionID,
        dijit.byId("promotionDialog"));
}

function show_help(name) {
    loadHtmlIntoDialog("/shop/help/" + name,
        dijit.byId("show_helpDialog"));
}

function back_toForm(frmName){
	window.location.href=frmName;
}

