dojo.registerModulePath("swit", "../../../swit");
dojo.require("dojo.cookie");
dojo.require("dijit.dijit");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.layout.LayoutContainer");
dojo.require("dijit.Dialog");
dojo.require("swit.Cart");
dojo.require("swit.OrderCart");

function getPage(n) {
	var q = dojo.query("#cart .switContainerCart");
	if (dojo.style(q[0], 'display') != 'none'){
		dojo.style(q[0], 'display', 'none');
	}
	dijit.containerCart.isShowing = false;
	dojo.byId("content").style.display = '';
	dijit.byId('page1').setHref(n.href);
}

function put(item){
	dijit.managerCart.putCSV(item);
	dijit.managerCart.sumItems()
};

function rem(item){
	dijit.managerCart.remove(item);
};

function quit() {

	var getArgs = {
		url: "destroy.php"
	}
	var getHandler = dojo.xhrPost(getArgs);
		getHandler.addCallback(function(html){
		return html;
	});

	dijit.managerCart.destroyAll();
	if (dijit.managerCart.notPut == true){
		dijit.orderCart.backToCart();
	}
	dojo.byId("new").style.display = '';
	dojo._destroyElement(dojo.byId("user").firstChild);
	dojo.byId("user").style.display = 'none';
	dojo.query('#login input').forEach(function(item){item.value = '';});
	dojo.query('#regCart .clear').forEach(function(item){item.value = '';});
}

var newWindow;
function makeNewWindow(url, name, width, height) {
    var windowHeight = height+34;
    var windowWidth = width+4;
    var left = parseInt((screen.availWidth/2)-(windowWidth/2));
    var top  = parseInt((screen.availHeight/2)-(windowHeight/2));
    var windowFeatures = "height="+windowHeight+", width="+windowWidth+", resizable=0, left="+left+", top="+top+", screenX="+left+", screenY="+top;
    newWindow = window.open("", name, windowFeatures);
    writeToWindow(url);
}
function writeToWindow(url) {
    var newContent = "<html><head><title>фотография</title><style>* {margin: 0;padding: 0;}</style></head>";
    newContent += "<body style='text-align:center;padding-top: 2px;background: #22196d;'><img src='"+url+"' />";
    newContent += "<br /><button style='margin: 4px auto;background: #a5bde7;font-weight: bold;color: #22196d;' onclick='window.close();'>Закрыть</button></body></html>";
    newWindow.document.write(newContent);
    newWindow.document.close();
}
function reg(form, session) {
    if (session) {
        var getArgs = {
            url: "session.php",
            headers: {
                Cookie: 'PHPSESSID='+session
            }
        }
    } else {
        var getArgs = {
            url: "registration.php",
            form: form,
            content: { submit: ""}
        }
    }
    var getHandler = dojo.xhrPost(getArgs);
    getHandler.addCallback(function(html){
        dojo.publish('topicCart', [html]);
        var tt = dojo.fromJson(html);
        var text = '<p style="margin: 4px 1em;">Здравствуйте ' + tt.name + ' ' + tt.fam + '<br />' + 'Ваш id = ' + tt.id + '<button class="quit" onclick="quit(); return false;">&nbsp;</button></p>';
        if(tt.id!=null) {
            dojo.byId("user").style.display = '';
            dojo.byId("user").innerHTML = text;
            dojo.byId("new").style.display = 'none'
            dojo.byId('regCart').style.display = 'none';
            dijit.managerCart.goToOrder();}
        return html;
    });
}
function generate_receipt(t, pdf) {
    if (pdf) {
        t.href = 'generate_receipt.php?submit_pdf&order='+dijit.managerCart.order;
    } else {
        t.href = 'generate_receipt.php?order='+dijit.managerCart.order;
    }
}

/*
 *проверяет наличие фото в корзине и выводит соответствующий текст
 * TODO: не соответсвует требованиям интернациональности и доступности
*/
function parseCart(){
	var cart = new Array();
	dojo.query('#cart tbody td.name').forEach(
		function(item){cart.push(dojo.string.trim(item.innerHTML));}
	);
	var pre = dojo.query('.photo pre').forEach(
		function(item){
			var from = dojo.string.trim(item.innerHTML).split(',');
			var k = dojo.indexOf(cart, from[0]);
			item.parentNode.lastChild.nodeValue = (k > -1)?'Товар в корзине':'Добавить в корзину';
		}
	);
}
/*
 *срабатывает когда происходит загрузка страницы
*/
function parseLoad(){
	dojo.query('#content a.corzina').connect("onclick", parseCart);
	parseCart();
}


function cart(close) {
	parseCart();
	var content = dojo.byId("content");
	if(content.style.display == 'none'){
		content.style.display = '';
	}else{
		content.style.display = 'none';
	}
	dijit.containerCart.open();
}
dojo.addOnLoad(function(){

var t = dojo.cookie("PHPSESSID");
if (t) {
    reg(null, t);
}
});