﻿var Album = (function() {
    var __construct = function(htmlObj, prpBox) {
        var _queue = Array();
        var me = this;

        this.div = htmlObj;
        htmlObj[0].album = this;
        this.properties = prpBox;
        this.product = "10x15";
        this.add = function(upl) {
            form = upl[0];
            _queue.push(new Photo(me));
            form.onupload = _queue[_queue.length - 1].uploadfinish;
            form.onstart = _queue[_queue.length - 1].uploadstart;
            form.onerror = _queue[_queue.length - 1].uploaderror;
            
            if(typeof form.uploadFinishCallback == "function"){
                _queue[_queue.length - 1].uploadFinishCallback = form.uploadFinishCallback;
            }
            if(typeof form.uploadErrorCallback == "function"){
                _queue[_queue.length - 1].uploadErrorCallback = form.uploadErrorCallback;
            }

            var name = $(form).find("input[name=filephoto]").val();
            if(name == "") name = $(form).find("input[name=urlphoto]").val();
            name = name.match(/([^\\/]+)\.(.{1,5})$/);
            if(!(name[2].toLowerCase() in {"jpg":"","jpeg":"","gif":"","bmp":"","png":"","zip":"","rar" :""})) {
                alert("Извините, но этот тип файлов не поддерживается.\nВы можете загрузить фотографии в форматах .jpg, .jpeg, .gif, .bmp, .png или архивы в форматах .zip, .rar.\nМаксимальный размер одного файла 150 Мб.");
                  return false;
            }

            _queue[_queue.length - 1].createBox(0, name[0]);
            _queue[_queue.length - 1].queueId = _queue.length - 1;
            return true;
        };
        this.remove = function(Photo) {
            if(Photo.order_product > 0) $.post("explorer/RemoveFromOrder", { order_cart_uid: Photo.order_product } );
            /*_queue.splice(Photo.queueId, 1);*/
            for(var i=0; i<_queue.length; i++){
              if(_queue[i]==Photo){
                _queue.splice(i, 1);
                delete Photo;
                break;
              }
            }
/*          console.log(_queue.length);
          console.log(Photo.queueId);*/
            UserCart.recalculate(me);
        };

        this.photos = function(num) {
            if (num < _queue.length) {
                return _queue[num];
            } else {
                return false;
            }
            ;
        };
        this.selected = function() {
            return me.div.find('.photo_wrap.ui-selected');
        };
        this.pimport = function(photos) {
            for (var key in photos) {
                _queue.push(new Photo(me));
                var photo = _queue[_queue.length - 1];

                photo.path = photos[key].thmb;
                photo.title = photos[key].title;
                photo.height = photos[key].height;
                photo.width = photos[key].width;
                photo.camera = photos[key].camera;
                photo.name = photos[key].name;
                photo.ok = photos[key].accept;
              
                photo.order_product = photos[key].order_cart_uid;

            /*photo.format();*/
                photo.paper(photos[key].paper);
                photo.frame(photos[key].frame);
                photo.correction(photos[key].correction);
                photo.urgent(photos[key].urgent);
                photo.comment(photos[key].comment);
                photo.quantity(photos[key].quantity);
                photo.productUid(photos[key].product_uid);

                photo.createBox(0, "");
                photo.createBox(1);
                photo.createBox(2);
                photo.queueId = _queue.length - 1;
            }
            UserCart.recalculate(me);
        };
    };

    return __construct;

})();


var Photo = (function() {
    var trans = [];
    for (var i = 0x410; i <= 0x44F; i++)
      trans[i] = i - 0x350; // А-Яа-я
    trans[0x401] = 0xA8;    // Ё
    trans[0x456] = 0xB3;    // і
    trans[0x406] = 0xB2;    // І
    trans[0x457] = 0xBF;    // ї
    trans[0x407] = 0xAF;    // Ї
    trans[0x454] = 0xBA;    // є
    trans[0x404] = 0xAA;    // Є
    trans[0x491] = 0xB4;    // ґ
    trans[0x490] = 0xA5;    // Ґ
  
    var escapeOrig = window.escape;
  
    window.escape = function(str){
      var ret = [];
      // Составляем массив кодов символов, попутно переводим кириллицу
      for (var i = 0; i < str.length; i++){
        var n = str.charCodeAt(i);
        if (typeof trans[n] != 'undefined')
          n = trans[n];
        if (n <= 0xFF)
          ret.push(n);
      }
      return escapeOrig(String.fromCharCode.apply(null, ret));
    } 
    var __construct = function(album) {
        var me = this;
        this.path = "";
        this.title = "";
        this.height = "";
        this.width = "";
        this.camera = "";
        this.ok = 0;
        this.order_product = 0;
        this.name = "";

        var _format;
        var _paper;
        var _frame;
        var _correction;
        var _comment;
        var _quantity;
        var _productUid;
        var _urgent = false;
        this.div = undefined;

        this.album = album;
        this.format = function(val) {
            return $(".photo_format option[value="+me.productUid()+"]").text();
        };
        this.productUid = function(val) {
          if (typeof val == "undefined") {
            return (typeof _productUid == "undefined")? me.getProductUid() : _productUid;
          }
            var needRecalc = (_productUid != val);
            _productUid = val;
            if (needRecalc) UserCart.recalculate(me.album);
        };

        this.remove = function() {
            me.div.remove();
            me.album.remove(me);
        };

        this.paper = function(val) {
            if (typeof val == "undefined") return _paper;

            _paper = val;

        };
        this.frame = function(val) {
            if (typeof val == "undefined") return _frame;
            _frame = val;
        };
  
        this.sizeOk= function(val) {
            if (typeof val == "undefined") return parseInt(me.ok);
            var needRecalc = (me.ok != val);
            me.ok = val;
            if (needRecalc) UserCart.recalculate(me.album);
            if(me.ok=="1"){
                me.div.removeClass('badsize');
            }else{
                me.div.addClass('badsize');
            }
        };

        this.correction = function(val) {
            if (typeof val == "undefined") return _correction;
            var needRecalc = (_correction != val);
            _correction = val;
            if (needRecalc) UserCart.recalculate(me.album);
        };
        this.urgent= function(val) {
            if (typeof val == "undefined") return _urgent;
            var needRecalc = (_urgent!= val);
            _urgent= val;
            if (needRecalc) UserCart.recalculate(me.album);
        };
        this.comment = function(val) {
            if (typeof val == "undefined") return _comment;
            _comment = val;
        };
        this.quantity = function(val) {
            if (typeof val == "undefined") return _quantity;
            var needRecalc = (_quantity != val);
            _quantity = val;
            if (needRecalc) UserCart.recalculate(me.album);
        };

        this.createBox = function(state, filename) {
            switch (state) {
                case 0:
                    me.div = $('<div class="photo_load">' +
                               '<div class="photo empty">' +
                               '<div class="title"> &nbsp;' + filename + '</div>' +
                               '<div class="waiting">' +
                               '<img src="design/img/waiting.png" alt="ожидание начала загрузки фотографии"/><br/>ожидание загрузки' +
                               '</div>' +
                               '</div>' +
                               '<div class="options"></div>' +
                               '</div>');
                    $(this.album.div).find(".add").parent().after(me.div);
                    $("#upload").append(me.div);
                    me.div.get(0).photo = me;
                    break;
                case 1:
                    me.div.find('div.waiting').html('<img src="design/img/progress.gif" alt="загрузка фотографии..."/><br/>загрузка');
                    break;
                case 2:
                    var myimage = new Image;
                    myimage.onload = function() {
                        me.div.attr('class', 'photo_wrap');
                        me.div.html('<div class="photo" style="background:url(\'' + me.path + '\') center bottom no-repeat;"><div class="icon"></div></div>' +
                                    '<div class="options"></div>');
                        me.printOptions();
                    };
                    myimage.onerror = function() {
                        me.uploaderror();
                    };
                    myimage.src = (me.path);
                    me.div.click(function(e) {
                        if(e.ctrlKey==false)
                            me.album.div.find(".photo_wrap.ui-selected").removeClass("ui-selected");
                        me.div.toggleClass("ui-selected");
                        me.album.properties.show(me.album);
                    });
                    break;
                case 3:
                    me.div.attr('class', 'photo_wrap');
                    me.div.find('div.waiting').html('<img src="design/img/bad.png" alt="ошибка загрузки"/><br/>' + filename);
                    me.div.find('div.options').html('<a href="javascript:void(0)" class="close_button" title="Удалить фотографию из заказа"></a>');
                    me.div.find('.close_button').click(function() {
                            me.remove();
                        });
                    break;
            };

        };
       
        this.printOptions = function (){
            me.div.find(".options").html('<div class="options_txt">' +
            ((me.productUid()<9 || me.productUid()>46)?
            ((me.quantity()>1)? me.quantity()+" шт. ":"")+
            me.format().replace(/ /g,"") + " " + 
            ((me.paper()==45559)?Localization.mate:Localization.glance) + " " +
            ((me.frame()==1 || me.correction()==1)?Localization.wiz + "&nbsp;" : "") +
            ((me.frame()==1)?Localization.frame+" ":"")+ 
            ((me.correction()==1)?
            ((me.frame()==1)?Localization.and+" ":"")+ 
            Localization.correction+" ":"")
             : me.name)+'</div>'+'<a href="javascript:void(0)" class="close_button" title="Удалить фотографию из заказа"></a>');
            me.div.find('.close_button').click(function() {
                me.remove();
            });
            me.sizeOk(me.ok);
 
        };

        this.uploaderror = function () {
          window.location.href = window.location.pathname; 
            me.uploadErrorCallback();
            me.ok = -1;
            me.createBox(3, "Ошибка при закачке файла.");
        };

        this.uploadstart = function (form) {
            $(form).append('<input type="hidden" name="product" value="' + me.productUid() + '">');
            me.createBox(1);
        };
        this.uploadfinish = function (info) {
            alert("upload finish");
            me.uploadFinishCallback();
            if (info.error) {
                me.ok = -1;
                me.createBox(3, info.error);
                return;
            }
            if(typeof info.length == "undefined"){
                me.path = info.thmb;
                me.title = info.title;
                me.height = info.height;
                me.width = info.width;
                me.camera = info.camera;
                me.size = info.size;
                me.ok = info.accept;
              
                me.order_product = info.order_cart_uid;

                _productUid = me.getProductUid();
                _paper = "45559";
                _frame = false;
                _correction = false;
                _urgent= false;
                _comment = "";
                _quantity = 1;

                UserCart.recalculate(me.album);

                me.createBox(2);
            }else{
                me.album.pimport(info);
                me.remove();
            }
        };
        this.getProductUid = function(){
          var uid = window.location.href.split("~");
          if(typeof uid[1] != "undefined") return parseInt(uid[1]);
            else return 2;
            
        };
        this.uploadFinishCallback = function(){};
        this.uploadErrorCallback = function(){};
    };

    return __construct;

})();


var PropertiesBox = (function() {
    var __construct = function() {
        this.div = $("#photo_settings");
        var me = this;
        this.on = false;
        this.photos = {};
        this.show = function(album) {
            if (me.on) {
                me.hide(false);
            }
            me.photos = album.selected();
            if(me.photos.length==1 && me.photos.get(0).photo.productUid() in photoBooksPages){
                return;
            }else if(me.photos.length==1 && me.photos.get(0).photo.productUid() in {"31":"","33":"","35":""}){
                $("#pohcolor").show();
            }else{
                $("#pohcolor").hide();
            }
            me.getValues(me.photos);

            var dtop = $(window).scrollTop() - $("#top").innerHeight() - parseInt(me.div.css("margin-top"));
            if(dtop < $("#cart").height()) dtop = $("#cart").height();
            if(dtop > $("#upload").height()) dtop = $("#upload").height() - me.div.height();
            me.div.css("top",dtop + "px"); 
           
            me.div.fadeIn(300);
            me.on = true;
        };
        this.hide = function(save) {
            if(save) me.saveValues();
            me.div.fadeOut(100);
            me.on = false;
        };

        this.getValues = function() {
            var photo = me.photos;
            var pht;
            if (parseInt(photo.length)<2) {
              
                pht = photo.get(0).photo;
                if (pht.width > 0) me.div.find(".photo_dim").text(pht.height + "x" + pht.width);
                me.div.find(".warning").css("display", (pht.ok=="1")? "none" : "").text("Размер изображения недостаточен для печати фото формата "+me.div.find(".photo_format option[value="+pht.productUid()+"]").text()+"!");
                            
                me.div.find(".photo_format").val(pht.productUid());
                me.div.find(".photo_paper").val(pht.paper());
                me.div.find(".photo_frame").attr("checked", (pht.frame()==1)?true:false);
                me.div.find(".photo_correction").attr("checked", (pht.correction()==1)?true:false);
                me.div.find(".photo_comment").val(pht.comment());
                me.div.find(".photo_quantity").val(pht.quantity());
                me.div.find(".urgent").attr("checked", (pht.urgent()==1)?true:false);
            } else {
                me.div.find(".photo_format").val(2);
                me.div.find(".photo_paper").val(0);
                me.div.find(".photo_frame").attr("checked", false);
                me.div.find(".photo_correction").attr("checked", false);
                me.div.find(".photo_comment").val("");
                me.div.find(".photo_quantity").val(1)
            }
        };
        this.saveValues = function() {
          var obj=Array();
            me.photos.each(function(i) {
              obj={"order_product_uid":this.photo.order_product};
                obj['product_uid']=(this.photo.productUid()<9 
                                    ||this.photo.productUid()>46 )? me.div.find(".photo_format").val() : this.photo.productUid();
                this.photo.productUid(obj['product_uid']);
                obj['paper'] = me.div.find(".photo_paper").val() || 0;
                this.photo.paper(obj['paper']);
                            
                obj['frame'] = me.div.find(".photo_frame").is(':checked');
                this.photo.frame(obj['frame']);
                obj['correction'] = me.div.find(".photo_correction").is(':checked');
                this.photo.correction(obj['correction']);
                obj['urgent'] = me.div.find(".urgent").is(':checked');
                this.photo.urgent(obj['urgent']);
                obj['comment'] = this.photo.comment(); //me.div.find(".photo_comment").val() || "";
                //this.photo.comment(obj['comment']);
                obj['quantity'] = me.div.find(".photo_quantity").val();
                if(this.photo.productUid() in photoBooksUid){
                  while (pht = this.photo.album.photos(i++)) {
                    if(pht.productUid()==photoBooksUid[this.photo.productUid()]){
                      pht.quantity(pht.quantity()/this.photo.quantity()*obj['quantity']);
                      $.post("explorer/Site_SaveProductOptions",{"order_product_uid":pht.order_product,
                                                                 "quantity":pht.quantity(),
                                                                 'product_uid':pht.productUid(),
                                                                 'paper':0,
                                                                 'frame':0,
                                                                 'correction':0,
                                                                 'urgent':0,
                                                                 'comment':0},function(data){},'text'); 
                    }
                  }
                }
                this.photo.quantity(obj['quantity']);
                var pht = this;
                $.post("explorer/Site_SaveProductOptions",obj,function(data){pht.photo.sizeOk(data.accept);},'json');
              
              
              
                this.photo.printOptions();
            });
          
          return obj;
        };


    };
    return __construct;
})();

var UserCart = {
    def_price : 0,
    def_count : 0,  
    recalculate : function(album) {
        if(typeof PriceList == "undefined"){
           setTimeout(function(){UserCart.recalculate(album)},200);
           return;
        }
        var count = this.def_count;
        var i = 0;
        var price = this.def_price;
        var pht;
        while (pht = album.photos(i++)) {
            if (pht.sizeOk() != 1) continue;
            var quantity = pht.quantity();
            price += parseFloat(PriceList[pht.productUid()])* quantity 
                     + pht.correction()* parseFloat(PriceList["45"])
                     + pht.urgent() * parseFloat(PriceList["46"]);
            count += parseInt(quantity);
        }
        UserCart.show(price, count);
    },
    show : function(price, count) {
        var full = parseInt(price);
        var coins = (Math.round(parseFloat(price - full) * 100) + 100) + "";
        $("#sum").text(full);
        $("#coins").text("," + coins.substr(1, 2));
        $("span.num").text(count);
    }
};
var photoBooksPages = {"22":"21","24":"23","27":"25","28":"26","30":"29","32":"31","34":"33","36":"35","38":"37","40":"39", "42":"41"};
var photoBooksUid = {"21":"22","23":"24","25":"27","26":"28","29":"30","31":"32","33":"34","35":"36","37":"38","39":"40", "41":"42"};

$.getScript("explorer/DataExporter");
$(function() {

    Albm = new Album($("#upload"), new PropertiesBox());
    $("#upload").selectable({filter:".photo_wrap",autoRefresh:true,delay:50});
    $("#upload").bind("selectablestop", function() {
        if (Albm.selected().length > 0)
            $("#upload").attr("album").properties.show($("#upload").attr("album"));
    });
    $("#photo_settings").find(".OK").click(function() {
        $("#upload")[0].album.properties.hide(true);
    });
    $("#photo_settings").find(".Cancel").click(function() {
        $("#upload")[0].album.properties.hide(false);
    });

$.getScript("explorer/Site_PhotosInOrder");
    var PhotoUpload = new UploadManager("explorer/Site_UploadPhoto");
    PhotoUpload.onadd = Albm.add;
    PhotoUpload.onstart = function(upl) {
        upl[0][0].onstart(upl[0]);
    };
    PhotoUpload.onstartall = function() {
        $("a").not("a[href^='javascript:']").attr("target", "_blank");
        window.onbeforeunload=function(){return "На странице идет загрузка фото. Если закрыть или обновить страницу, загрузка прервется."};
    };
    PhotoUpload.onfinishall = function() {
        $("a").not("a[href^='javascript:']").attr("target", "_self");
        window.onbeforeunload=function(){};
    };
    PhotoUpload.onfinish = function(upl, data) {
        upl[0][0].onupload(data);
    };
    PhotoUpload.onerror = function(e) {
        e[1][0][0].onerror(e);
    };
      
    $("#addUpload").ajaxForm({
        beforeSubmit : PhotoUpload.add});

    });
  
 
  
