var projectId = "";
var widget_dialog ="";
var widget = null;
var photo_guid = "";
var width;
var height;

var directory = "/skins/EZP/100287/services";
// *************************************************************************************************************
// *************************************************************************************************************
// *************************************************************************************************************

var loaded = false;
function widgetReady()
{
	//alert("widget is ready");
	if(SKU!=null){
	    //widget.setSku(SKU);
	    //alert("LOADED SKU")
	    loaded = true;
	}
}
function projectLoaded()
{
	// alert("project was loaded");	
}

function saveComplete(projectId, thumbUrl)
{
	var sku = SKU;
	var quantity = $F('quantity');
    var params = 'photos=' + photo_guid + '&quantity=' + quantity + "&projectId=" + projectId + "&sku=" + sku;

    new Ajax.Request(
    	location.protocol + '//' + location.host + "/order/photo/",
        {
            method: "POST",
		            parameters: params,
		            onSuccess: updateOrderPrint
		}
	);    
}
		
function templateLoaded()
{
	widget.setPhoto({ id: "1", screenResUri: "http://photoecoz.com/stock/photo/" + photo_guid + "/?size=m" + session_string, printResWidth: width, printResHeight: height });
}
			
function SendSelectedSku()
{
	//get selected sku
	var selectBox = document.getElementsByName('projectSelect')[0];
	sku = selectBox.value;
	if (widget)
	{
		widget.setSku(sku);
	}
	else
	{
		createWidget();
	}
}
		
function createWidget(projectId){
    widget = ezp.apps.createTemplateApp({
        elementId: "configuratorDiv"
        ,width: 760
        ,height: 440
        ,sku: begin_sku
        ,readyCallback: widgetReady
        ,loadCallback: projectLoaded
        ,saveCallback: saveComplete
        ,templateLoadCallback: templateLoaded
        ,projectId: projectId
    });
}
var init_widget = function(){
    
    createWidget();
    change_product();
}

function updateOrderPrint(transport)
{
	saveToCartComplete();
	showAddToCartNotice();
	
}

function run_widget_script(){
	init_widget();
}

function saveAndAddToCart(win){
	widget.save();
}

function saveToCartComplete(){
	Dialog.closeInfo();
}

function show_photo_widget(){
	widget_dialog = Dialog.confirm({url: location.protocol + '//' + location.host + "/order/widget/" + photo_guid + "/", options: {method: 'get'}}, 
            {top: 10, width:790, height:570, className: "alphacube", okLabel: "Add to cart", cancelLabel:"Cancel", onOk: saveAndAddToCart, onShow: run_widget_script, zIndex:2000 });
}

function SetWidthHeight(in_width, in_height){
	width = in_width;
	height = in_height;
}

function AddToCart()
{
    // Call the server...
	photo_guid = main_photo_guid;
    show_photo_widget(main_photo_guid);
}

function SetProjectId(in_projectId, guid){
	projectId = in_projectId;
	AddToCartByGuid(guid);
}


function AddToCartByGuid(guid){
	photo_guid = guid;
	show_photo_widget();
}

var begin_sku = 10040;
var products = {'root':{
    'Prints':{'optgroup*Small format': '',
              'Size*4x6': {'Finish*Glossy': {'id':'10040', 'price': '$0.20'}, 'Matte': {'id':'10043', 'price': '$0.20'}, 'Lustre': {'id':'10048', 'price': '$0.23'}},
              'Size*5x7': {'Finish*Glossy': {'id':'10050', 'price': '$0.69'}, 'Matte': {'id':'10053', 'price': '$0.69'}, 'Lustre': {'id':'10061', 'price': '$0.73'}},
              'Size*8x10': {'Finish*Glossy': {'id':'10080', 'price': '$1.79'}, 'Matte': {'id':'10083', 'price': '$1.79'}, 'Lustre': {'id':'10090', 'price': '$2.14'}},
              'optgroup*Medium format': '',
              'Size*11x14': {'Finish*Glossy': {'id':'10091', 'price': '$2.92'}, 'Matte': {'id':'10093', 'price': '$2.92'}, 'Lustre': {'id':'10094', 'price': '$3.50'}},
              'Size*12x18': {'Finish*Glossy': {'id':'50050', 'price': '$6.22'}, 'Matte': {'id':'50051', 'price': '$6.22'}, 'Lustre': {'id':'50052', 'price': '$7.46'}},
              'optgroup*Large format': '',
              'Size*16x20': {'Finish*Glossy': {'id':'50100', 'price': '$9.30'}, 'Matte': {'id':'50101', 'price': '$9.30'}, 'Lustre': {'id':'50102', 'price': '$11.15'}}
             },
    'Gifts': {'Magnets': {'Size*2.5x3.5':{'id':'10195', 'price': '$3.58'},'3.5x5.0':{'id':'10196', 'price': '$4.73'}},
              'Keepsake Box': {'id':'10240', 'price': '$32.95'},
              'Photopanel with Easel': {'Size*5x7':{'id':'10570', 'price': '$10.94'},'8x10':{'id':'10571', 'price': '$21.95'}}
             }
    }};
function change_product(){
    create_select('root', $('products').options[$('products').selectedIndex].value);
}


function parseProducts(strCrumbs){

    data = strCrumbs.split(':');

    var temp = products;

    for(x=0;x<data.length;x++){
        //alert(data[x]);
        temp = temp[data[x]];
    }
    return temp
};
var SKU = null;

function create_select(strCrumbs, strCurrent){
    var strRoot = strCrumbs+":"+strCurrent;
    var depth = strRoot.split(':').length;
    var p_list = parseProducts(strRoot);
     if(strCurrent=='id')
         return
    if($('div_'+ depth)){
        $('div_'+ depth).remove();
    }
    
    if(p_list['id']){
        if (widget)
	    {  
	        // Show price
	        //p_list['price']
	        if($('price')){
	           $('price').update("&nbsp;&nbsp;&nbsp;&nbsp;Price per item: "+p_list['price']);
	        }else{
	           
	           el = new Element('span', { 'id': 'price'}).update("&nbsp;&nbsp;&nbsp;&nbsp;Price per item: "+p_list['price']);
	           prev_depth = depth - 1;
               $('div_'+prev_depth).insert(el);
	        }
	        if(loaded)
	           widget.setSku(p_list['id']);
	        SKU = p_list['id'];
	        $('sku').update(p_list['id']);
	    }
	    else
	    {
	        createWidget();
	    }
        return
    }
    div_el = new Element('span', {'id': 'div_'+depth});
    el = new Element('select', {'id': "sel_"+depth,'onchange':'create_select("'+ strRoot +'", $(this).value);'});
    var first = null;
    
    var label = null;
    var el_label = null;
    for(var key in p_list){
        var pieces = key.split('*');
        if(pieces[0]=="optgroup"){
            el_c = new Element('optgroup', {'label': pieces[1]});
            el.insert(el_c);
        }else{
	        if(first==null)
	            first = key;

	        var innerText = null;
	        if(pieces.length==2){
	            innerText = pieces[1];
	            label = pieces[0];
	            if(el_label==null){
	                el_label = new Element('span').update("&nbsp;&nbsp;"+label+":&nbsp;");
	            }
	        }else{
	            if(el_label==null){
	                el_label = new Element('span').update("&nbsp;&nbsp;");
	            }
	            innerText = pieces[0];
	        }
	        el_c = new Element('option',{'value':key}).update(innerText);
            el.insert(el_c);
        }
        
    }
    if(el_label!=null)
        div_el.insert(el_label);
    div_el.insert(el);
    
    var p_depth = depth -1;
    $('div_'+p_depth).insert(div_el);
    
    
    create_select(strRoot, first);

}

