map = '';
placemark = '';
map_status_id = 1; // 0 - hidden, 1 - visible
map_placemark = '';
map_x = 0;
map_y = 0;

var Site = {
    init: function() {
        $('body').ajaxError(function(event, XMLHttpRequest, ajaxOptions, thrownError) {
            //alert("Произошла ошибка при запросе к серверу: "+thrownError);
            alert("Произошла ошибка при запросе к серверу. Обратитесь к администратору сайта.");
        });


        $('div[id$=_popup]').each(function() {
            var formId = $(this).attr('id');
            var str = formId.substring(0, formId.lastIndexOf('_'));
            Site.attachShowForm('#'+formId, '.'+str+'_btn', '#'+str+'_form_close');
        });





        if ($.cookie("facebookMessageShown")==undefined) {      
                Site.showForm('#facebook_popup');
                $.cookie("facebookMessageShown", true, {expires: 356});
        }

		
		
		
		
		
		
		
    },
    extractModelErrors: function(attributes) {
        var result = '';
        for (attribute in attributes) {
            for (error in attributes[attribute]) {
                result += attributes[attribute][error]+' ';
            }
        }
        if (result != '') {
            result = result.substr(0, result.length-1);
        }
        return result;
    },
    attachShowForm: function(formId, showBtn, closeBtn) {
        $(showBtn).click(function() {   
            Site.showForm(formId)
        });
        $(closeBtn).click(function() {
            Site.hideCurrentForm();
        });
        $(closeBtn.replace('#','.')).click(function() {
            Site.hideCurrentForm();
        });
    },
    showForm: function(formId) {
        var showForm = false;
        if (formId != Site.overlay.formId) {
           showForm = true;
        }
        Site.hideCurrentForm();
        if (showForm) {
            var popupClass = $(formId).attr('class');
            Site.overlay.popupClass = popupClass;
            if (!Site.overlay.shown && popupClass && popupClass.indexOf('overlay') != -1) {
                 Site.overlay.show();
            }
            Site.overlay.formId = formId;
            if (popupClass && popupClass.indexOf('permanent') != -1) {
                Site.overlay.hideOnClick = false;
            }

            $(formId+'-form-errors').hide();

            if (popupClass && popupClass.indexOf('fade') != -1) {
                 $(formId).fadeIn();
            }else if (Site.overlay.popupClass && Site.overlay.popupClass.indexOf('payment_notes_popup') != -1) {
                $(Site.overlay.formId).show().animate( { marginBottom:  0, opacity:1 },300);
            }else {
                $(formId).show('scale');
            }
            $(formId.substring(0,formId.indexOf('_'))+'_form_errors').html('').css('display', 'none');
        }
    },
    hideCurrentForm : function() {
        if (Site.overlay.formId && Site.overlay.hideOnClick ) {
            if (Site.overlay.popupClass && Site.overlay.popupClass.indexOf('fade') != -1) {
                $(Site.overlay.formId).fadeOut();
            }else if (Site.overlay.popupClass && Site.overlay.popupClass.indexOf('payment_notes_popup') != -1) {
                $(Site.overlay.formId).animate( { marginBottom:  10, opacity:0 },400, '', function(){ $(this).hide()});
            }else {
                $(Site.overlay.formId).hide('scale');
            }
            Site.overlay.hide();
            Site.overlay.formId = '';
            Site.overlay.hideOnClick = true;
            Site.overlay.popupClass = '';
        }
    },
    overlay: {
        active: '',
        shown: false,
        formId: '',
        hideOnClick: true,
        popupClass: '',
	    show: function() {
		    var $el = $('<div id=\"overlay\"></div>').appendTo(document.body)
			    .addClass('overlayers').css({
				    width: this.width(),
				    height: this.height(),
                    zIndex: 10000,
                    display: 'none'
			    })
                .click(function() {
                    Site.hideCurrentForm();
                });

                if ( $.browser.msie ) {
                    $el.show();
                }else {
                    $el.fadeIn();
                }

	    },
	    hide: function() {
            $('#overlay').fadeOut(500, function() {$(this).detach()});
        },
	    width: function() {
		    if ($.browser.msie && $.browser.version < 7) {
			    var scrollWidth = Math.max(document.documentElement.scrollWidth, document.body.scrollWidth);
			    var offsetWidth = Math.max(document.documentElement.offsetWidth, document.body.offsetWidth);
			    if (scrollWidth < offsetWidth) {
				    return $(window).width()+'px';
			    } else {
				    return scrollWidth+'px';
			    }
		    } else {
			    return $(document).width()+'px';
		    }
	    },
	    height: function() {
		    if ($.browser.msie && $.browser.version < 7) {
			    var scrollHeight = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
			    var offsetHeight = Math.max(document.documentElement.offsetHeight, document.body.offsetHeight);
			    if (scrollHeight < offsetHeight) {
				    return $(window).height()+'px';
			    } else {
				    return scrollHeight+'px';
			    }
		    } else {
			    return $(document).height()+'px';
		    }
	    }
    },
    profile: {
        /*
        cities: {
            init: function() {
                $('.profile-city').change(function() {
                    $('.profile-city').attr('checked', false);
                    $(this).attr('checked', true);
                });
            }
        },
        preferences: {
            init: function() {
                $('.preferences-check-all').click(function() {
                    var id = $(this).attr('id').substr($(this).attr('id').indexOf('_')+1);
                    $('.preferences-folder_'+id).attr('checked', true);
                });
                $('.preferences-uncheck-all').click(function() {
                    var id = $(this).attr('id').substr($(this).attr('id').indexOf('_')+1);
                    $('.preferences-folder_'+id).attr('checked', false);
                });
            }
        },
        */
        loading: false,
        addToFavorites: function(coupon_id) {
            if (Site.profile.loading) return;
            if ($('#favoriteStar').attr('class') == 'deal_notes_favorites_ac') {
                Site.profile.removeFromFavorites(coupon_id);
                return;
            }
            Site.profile.loading = true;
            $.post("/favourites/add/",
                    {coupon_id: coupon_id},
                   function(data) {
                       if (data.result) {
                           $('#favoriteStar').attr('class','deal_notes_favorites_ac');
                           Site.message.show('Добавлено в избранное');
                           //$('#messageText').html('Добавлено в избранное');
                           //$('#message').css('opacity', 0).css('height', 0).show().animate({opacity:1,height:40}, 500).delay(800).animate({opacity:0, height:0}, 500,'swing',function() {Site.profile.loading = false;$('#message').hide()});
                       } else {
                           //$('#gift-form-errors').html(Site.extractModelErrors(data.errors)).css('display', 'block');
                       }

                   },
                   'json');
        },
        removeFromFavorites: function(coupon_id) {
            if (Site.profile.loading) return;
            if ($('#favoriteStar').attr('class') == 'deal_notes_favorites') {
                Site.profile.addToFavorites(coupon_id);
                return;
            }
            Site.profile.loading = true;
            $.post("/favourites/remove/",
                    {coupon_id: coupon_id},
                   function(data) {
                       if (data.result) {
                           $('#favoriteStar').attr('class','deal_notes_favorites');

                           Site.message.show('Удалено из избранного');
                           //$('#messageText').html();
                           //$('#message').css('opacity', 0).css('height', 0).show().animate({opacity:1,height:40}, 500).delay(800).animate({opacity:0, height:0}, 500,'swing',function() {Site.profile.loading = false;$('#message').hide()});
                       } else {
                           //$('#gift-form-errors').html(Site.extractModelErrors(data.errors)).css('display', 'block');
                       }
                   },
                   'json');
        },
        emailIsNotComfirmed: function() {
            Site.message.show('Пожалуйста, активируйте свою учетную запись');
                           //$('#messageText').html('Активируйте свой имейл');
                           //$('#message').css('opacity', 0).css('height', 0).show().animate({opacity:1,height:40}, 500).delay(800).animate({opacity:0, height:0}, 500,'swing',function() {Site.profile.loading = false;$('#message').hide()});
        }
    },
    iphone: {
        imgNum: 1,
        init: function() {
            setInterval(function() {
                $('.iphone_screen').fadeOut(700, function() {
                    Site.iphone.imgNum++;
                    if (Site.iphone.imgNum > 8) Site.iphone.imgNum = 1;
                    $('.iphone_screen').css('background', 'url(/img/iphone/'+Site.iphone.imgNum+'.png) 0 0 no-repeat');
                    $('.iphone_screen').fadeIn(1200);
                });
            }, 4000);
        }
    },
    message: {
        show: function(msg) {
            $('#messageText').html(msg);
            $('#message').css('opacity', 0).css('height', 0).show().animate({opacity:1,height:40}, 500).delay(800).animate({opacity:0, height:0}, 500,'swing',function() {Site.profile.loading = false;$('#message').hide()});
        }
    },
    payments: {
        send: function(offer_id, paymentSystem_id, paymentType_id) {
            if (offer_id > 0) {
                $.post("/payment/create/",
                    {offer_id: offer_id, paymentSystem_id:paymentSystem_id, paymentType_id: paymentType_id},
                    function(data) {
                           if (data.result) {
                               if (paymentSystem_id == 2) { //robokassa
                                   $('#rkOutSum').val(data.price);
                                   $('#rkInvId').val(data.paymentId);
                                   $('#rkDesc').val(data.paymentDescription);
                                   $('#rkSignatureValue').val(data.hash);
                                   $('#rkIncCurrLabel').val(data.paymentType);
                                   $('#rkCulture').val(data.lang);
                                   $('#robokassaForm').submit();
                               }else if (paymentSystem_id == 3) { //masterbank
                                   $('#mbOrder').val(data.paymentId);
                                   $('#mbAmount').val(data.price);
                                   $('#mbTerminal').val(data.terminal);
                                   $('#mbTimestamp').val(data.timestamp);
                                   $('#mbSign').val(data.hash);
                                   $('#masterbankForm').submit();
                               }

                               // create function for this
                               Site.showForm('#wait_popup');

                           } else {
                               Site.message.show(data.message);
                           }
                    },
                    'json'
                );
            }else if (offer_id == 0) {
                var depositValue = $('#depositValue').val();
                depositValue = depositValue.replace(',', '.');
                if (Number(depositValue) != depositValue) {
                    $('#deposit_form_errors').html('Введите сумму от 50 до 15000 руб.').show().css('height', 0).show().animate({height:22}, 300);
                    return;
                }else {
                    if (depositValue < 50) {
                        $('#deposit_form_errors').html('Минимальная сумма пополнение 50 руб.').show().css('height', 0).show().animate({height:22}, 300);
                        return;
                    }
                    else if (depositValue > 15000) {
                        $('#deposit_form_errors').html('Максимальная сумма пополнение 15000 руб.').show().css('height', 0).show().animate({height:22}, 300);
                        return;
                    }
                }

                depositValue = Math.abs(depositValue);
                $.post("/payment/deposit/",
                    {depositValue: depositValue, paymentSystem_id:paymentSystem_id, paymentType_id: paymentType_id},
                    function(data) {
                           if (data.result) {
                               if (paymentSystem_id == 2) { //robokassa
                                   $('#rkOutSum').val(data.price);
                                   $('#rkInvId').val(data.paymentId);
                                   $('#rkDesc').val(data.paymentDescription);
                                   $('#rkSignatureValue').val(data.hash);
                                   $('#rkIncCurrLabel').val(data.paymentType);
                                   $('#rkCulture').val(data.lang);
                                   $('#robokassaForm').submit();
                               }else if (paymentSystem_id == 3) { //masterbank
                                   $('#mbOrder').val(data.paymentId);
                                   $('#mbAmount').val(data.price);
                                   $('#mbTerminal').val(data.terminal);
                                   $('#mbTimestamp').val(data.timestamp);
                                   $('#mbSign').val(data.hash);
                                   $('#masterbankForm').submit();
                               }
                               
                               // create function for this
                               Site.showForm('#wait_popup');
                               
                           } else {
                               //$('#deposit_form_errors').html(data.message).css('display', 'block');
                               $('#deposit_form_errors').html(data.message).show().css('height', 0).show().animate({height:22}, 300);
                           }
                    },
                    'json'
                );
            }
        },
        sendWithEmail: function(offer_id, paymentSystem_id, paymentType_id) {
            if (offer_id > 0) {
                var email = $('#friendsEmail').val();

                $.post("/payment/create/",
                    {offer_id: offer_id, email: email, paymentSystem_id:paymentSystem_id, paymentType_id: paymentType_id},
                    function(data) {
                           if (data.result) {
                               if (paymentSystem_id == 2) { //robokassa
                                   $('#rkOutSum').val(data.price);
                                   $('#rkInvId').val(data.paymentId);
                                   $('#rkDesc').val(data.paymentDescription);
                                   $('#rkSignatureValue').val(data.hash);
                                   $('#rkIncCurrLabel').val(data.paymentType);
                                   $('#rkCulture').val(data.lang); 
                                   $('#robokassaForm').submit();
                               }else if (paymentSystem_id == 3) { //masterbank
                                   $('#mbOrder').val(data.paymentId);
                                   $('#mbAmount').val(data.price);
                                   $('#mbTerminal').val(data.terminal);
                                   $('#mbTimestamp').val(data.timestamp);
                                   $('#mbSign').val(data.hash);
                                   $('#masterbankForm').submit();
                               }

                               // create function for this
                               Site.showForm('#wait_popup');

                           } else {
                               $('#gift_form_errors').html(data.message).css('display', 'block');
                           }
                    },
                    'json'
                );
            }
        },
        checkBalance: function(offer_id) {
            $.post("/profile/checkBalance/",
                {offer_id: offer_id},
                function(data) {
                       if (data.result) {
                           Site.offers.offer_id = offer_id;
                           Site.showForm('#appinyPayment_popup');
                       } else {
                           //$('#gift_form_errors').html(data.message).css('display', 'block');
                           Site.message.show(data.message);
                       }
                },
                'json'
            );
        },
        checkBalanceWithEmail: function(offer_id) {
            var email = $('#friendsEmail').val();
            $.post("/profile/checkBalance/",
                {offer_id: offer_id, email: email},
                function(data) {
                       if (data.result) {
                           Site.offers.offer_id = offer_id;
                           Site.offers.email = email;
                           Site.showForm('#appinyPayment_popup');
                       } else {
                           $('#gift_form_errors').html(data.message).css('display', 'block');
                       }
                },
                'json'
            );
        }
    },
    offers: {
        offer_id: 0,
        userOffer_id: 0,
        email: '',
        sendingData: false,
        buy: function() {
            if (Site.offers.sendingData) return;
            Site.offers.sendingData = true;
            $.post("/offer/buy/",
                {offer_id: Site.offers.offer_id, email: Site.offers.email},
                function(data) {
                    if (data.result) {
                        if (data.email) location.href = '/mycoupons/gifted/';
                        else location.href = '/mycoupons/';
                    } else {
                        $('#appinyPayment_form_errors').html(data.message).css('display', 'block');
                        Site.offers.sendingData = false;
                    }
                },
                'json'
            );
        },
        checkUserOffer : function(userOffer_id) {
            Site.offers.userOffer_id = userOffer_id;
            $.post("/useroffer/check/",
                {userOffer_id: userOffer_id},
                function(data) {
                    if (data.result) {
                        //location.href = '/mycoupons/';
                        if (data.paymentType_id == 2){
                            $('#paymentType2').show();
                        }else {
                            $('#paymentType2').hide();
                        }
                        Site.showForm('#return_popup');
                    } else {
                        //$('#appinyPayment_form_errors').html(data.message).css('display', 'block');
                        //Site.offers.sendingData = false;
                    }
                },
                'json'
            );
        },
        returnOffer : function(paymentType_id) {
            $.post("/useroffer/return/",
                {userOffer_id: Site.offers.userOffer_id, paymentType_id: paymentType_id},
                function(data) {
                    if (data.result) {
                        window.location = location.href;
                    } else {
                        $('#return_form_errors').html(data.message).css('display', 'block');
                        //Site.offers.sendingData = false;
                    }
                },
                'json'
            );
        },
        showRenounceForm : function(userOffer_id) {
            Site.offers.userOffer_id = userOffer_id;
            Site.showForm('#renounce_popup');
        },
        renounceOffer : function() {
            $.post("/useroffer/renounce/",
                {userOffer_id: Site.offers.userOffer_id},
                function(data) {
                    if (data.result) {
                        window.location = location.href;
                    } else {
                        $('#return_form_errors').html(data.message).css('display', 'block');
                        //Site.offers.sendingData = false;
                    }
                },
                'json'
            );
        },
        showUploadCodesForm : function(offer_id) {
            Site.offers.offer_id = offer_id;
            //createUploader();
            Site.showForm('#uploadCodes_popup');
        },
        appoveUpload : function(licensePack_id) {
            $.post("/partner/generateCodes/",
                {licensePack_id: licensePack_id},
                function(data) {
                    if (data.result) {
                        window.location = '/partner/licenses/'+data.licensePack_id+'/';//location.href;
                        //alert(data.message);
                    } else {
                        alert(data.message);
                        //$('#uploadCodes_form_errors').html(data.message).css('display', 'block');
                        //Site.offers.sendingData = false;
                    }
                },
                'json'
            );
        }
        /*,
        uploadCodes : function() {
            $.post("/offer/uploadCodes/",
                {offer_id: Site.offers.offer_id, count: $('#codesCount').val()},
                function(data) {
                    if (data.result) {
                        //window.location = location.href;
                    } else {
                        $('#uploadCodes_form_errors').html(data.message).css('display', 'block');
                        //Site.offers.sendingData = false;
                    }
                },
                'json'
            );
        }   */

        /*,
        buyForFriend: function() {
            if (Site.offers.sendingData) return;
            Site.offers.sendingData = true;
            $.post("/offer/buy/",
                {offer_id: Site.offers.offer_id, email: Site.offers.email},
                function(data) {
                    if (data.result) {
                        location.href = '/mycoupons/';
                    } else {
                        $('#appinyPayment_form_errors').html(data.message).css('display', 'block');
                        Site.offers.sendingData = false;
                    }
                },
                'json'
            );
        }*/
    }
    /*
    buyCoupon: function(coupon_id) {
        $('#gift-info').html('');
        $('#gift-form-errors').html('');
        $.post("/profile/buy/",
                {coupon_id: coupon_id},
               function(data) {
                   if (data.result) {
                       $('#gift-info').html(data.html);
                   } else {
                       $('#gift-form-errors').html(Site.extractModelErrors(data.errors)).css('display', 'block');
                   }
               },
               'json');
        return false;
    }*/
}
/*
var initMap = function() {
    // Создание экземпляра карты и его привязка к созданному контейнеру
    if (map_status_id) {
        jQuery("#noCoordinates").hide();
        jQuery("#YMapsID").show();

        if (!map) {
            map = new YMaps.Map(YMaps.jQuery("#YMapsID")[0]);
            // Добавление элементов управления
            map.addControl(new YMaps.TypeControl());
            map.addControl(new YMaps.ToolBar());
            map.addControl(new YMaps.Zoom());
            map.addControl(new YMaps.MiniMap());
            map.addControl(new YMaps.ScaleLine());
            map.addControl(new YMaps.SearchControl());
        }
        if (placemark) {
            map.removeOverlay(placemark);
        }

        // Установка для карты ее центра и масштаба
        map.setCenter(new YMaps.GeoPoint(map_x, map_y), 13);
        // Создание метки с всплывающей подсказкой
        placemark = new YMaps.Placemark(new YMaps.GeoPoint(map_x, map_y), {hasHint: 1});
        placemark.name = map_placemark;
        // Добавление метки на карту
        map.addOverlay(placemark);
        // Открытие балуна
        placemark.openBalloon();


        // Открытие балуна
        //map.openBalloon(new YMaps.GeoPoint(37.64, 55.76), "Москва");
    }else {
          jQuery("#YMapsID").hide();
          jQuery("#noCoordinates").show();
    }

}*/
function editComment(comment_id) {
    var html = $('#comment_'+comment_id).html();

    html = html.replace(/<span>/gi, '[span]');
    html = html.replace(/<\/span>/gi, '[/span]');
    html = html.replace(/<strong>/gi, '[strong]');
    html = html.replace(/<\/strong>/gi, '[/strong]');
    html = html.replace(/<br>/gi, "\r\n");
    html = html.replace(/<br\/>/gi, "\r\n");
    html = html.replace(/<br \/>/gi,"\r\n");

    html = html.replace(/<!--noindex-->/gi,'');
    html = html.replace(/<!--\/noindex-->/gi,'');

    html = html.replace(/<\/a>/gi, '[/url]');
    html = html.replace(/ref="nofolllow" href="/gi, '');
    html = html.replace(/">/gi, ']');
    html = html.replace(/<a /gi, '[url=');

    
    $('div[id^=comment_]').each(function(n,element){
            $(element).show();
    });
    $('#comment_'+comment_id).hide();
    $('#comment_edit_'+comment_id).append($('.post_editcomment'));
    $('.post_editcomment').show();
    $('#post_comment_body').val(html);
    $('#post_comment_id').val(comment_id);
}
function deleteComment(comment_id) {
    if (confirm("Уверены, что хотите удалить данный комментарий?")) {
        $.ajax({
            url: "/comment/delete",             // указываем URL и
            data : { id:  comment_id},
            dataType : "json",                     // тип загружаемых данных
            success: function (data, textStatus) { // вешаем свой обработчик на функцию success
                 window.location.reload();
            }
        });
    }

}/*
function copy(inElement) {
  if (inElement.createTextRange) {
    var range = inElement.createTextRange();
    if (range && BodyLoaded==1)
      range.execCommand('Copy');
  } else {
    var flashcopier = '/swf/flashcopier';
    if(!document.getElementById(flashcopier)) {
      var divholder = document.createElement('div');
      divholder.id = flashcopier;
      document.body.appendChild(divholder);
    }
    document.getElementById(flashcopier).innerHTML = '';
    var divinfo = '<embed src="_clipboard.swf" FlashVars="clipboard='+encodeURIComponent(inElement.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashcopier).innerHTML = divinfo;
  }
}  */




window.fbAsyncInit = function() {



$(document).ready(function(){

    FB.init({
        appId   : 137932469627518,
        //session : 18944, // don't refetch the session when PHP already has it
        status  : true, // check login status
        cookie  : true, // enable cookies to allow the server to access the session
        xfbml   : true // parse XFBML
});

 //alert('ok')
// whenever the user logs in, we refresh the page
    /*
 FB.Event.subscribe('auth.login', function() {
     $('#sm').val('facebook');
     $('#register-form').submit();
 });
*/
 $('#facebook-login-handler').click(
         function(){
             FB.getLoginStatus(function(response) {
                 if (response.session && response.status=='connected') {
                     $('#sm').val('facebook');
                     $('#register-form').submit();
                  } else {
                    fblogin();
                  }
             });
         }

 );
 });

 };





 function fblogin(){
    FB.login(function(response) {
             if (response.session) {
                 $('#sm').val('facebook');
                 $('#register-form').submit();
             }
     }, {perms:'email,user_birthday,user_location,user_hometown,publish_stream'});
 }


$(document).ready(function() {
    $('a[class^=landing_]').click(function() {
        if (Site.overlay.formId != '') {
            $(Site.overlay.formId).hide('highlight');
        } else {
           Site.overlay.show();
        }
        $('#sm').val('');
        if($(this).attr('id') == 'reg_button') {
             $('#reginvite_task').val('register');
        }else {
             $('#reginvite_task').val('');
        }
        $('#reginvite-form-errors').hide();
        if ($(this).attr('rel') == '' && $(this).attr('id') != 'reg_button') {
            $('#yourchoice-box').show();
            $('#reginvite').css('height', '250px');
            $('#yourchoice').val('введите ваш вариант сюда...');
        }else {
            $('#yourchoice-box').hide();
            $('#reginvite').css('height', '200px');
            $('#yourchoice').val($(this).attr('rel'));
        }
        /*Site.overlay.formId = '#reginvite';
        $('reginvite-form-errors').css('display', 'none');
        $('#reginvite').show('highlight');*/
    });


    //setCounters();
});

function setCounters() {
    $('div[id^=countdown]').each(function() {
        $(this).countdown({date: $(this).html()});
        $(this).css('visibility', 'visible');
    });
}
     /*
	function ajaxFileUpload()
	{
		$("#loading")
		.ajaxStart(function(){
			$(this).show();
		})
		.ajaxComplete(function(){
			$(this).hide();
		});

		$.ajaxFileUpload
		(
			{
				url:'/partner/checkfile/',
				secureuri:true,
				fileElementId:'fileToUpload',
				dataType: 'json',
				data:{name:'logan', id:'id'},
				success: function (data, status)
				{     alert('123');
                       if (data.result) {

                           $('#uploadResult').html(data.data)
                       } else {
                           $('#uploadCodes_form_errors').html(data.message).css('display', 'block');
                       }
				},
				error: function (data, status, e)
				{
					alert(e);    alert('123');
				}
			}
		)

		return false;

	}*/
        function createUploader(){
            var uploader = new qq.FileUploader({
                element: document.getElementById('file-uploader-demo1'),
                action: '/partner/checkfile/',
                onSubmit: function(id, fileName){
                    if (isNaN($('#codesCount').val()) || $('#codesCount').val()<=0) {
                        alert('Введитк кол-во лицензий');
                        return false;
                    }
                    uploader.setParams({
                        offer_id: Site.offers.offer_id,
                        count: $('#codesCount').val()
                    });
                },
                onComplete: function(id, fileName, responseJSON){
                    if (!responseJSON.result) alert(responseJSON.message);
                    else $('#uploadResult').html(String(responseJSON.data));
                },
                allowedExtensions: ['txt','zip'],
                debug: true
            });
        }

        // in your app create uploader as soon as the DOM is ready
        // don't wait for the window to load
        window.onload = createUploader;



       /*
    	$(function(){
		var btnUpload=$('#uploadCodes_btn');
		//var status=$('#status');
		new AjaxUpload(btnUpload, {
			action: '/partner/checkfile/',
			name: 'uploadfile',
			onSubmit: function(file, ext){
				 if (! (ext && /^(txt|zip)$/.test(ext))){
                    // extension is not allowed
					//status.text('Only JPG, PNG or GIF files are allowed');
					return false;
				}
				status.text('Uploading...');
			},
			onComplete: function(file, response){
				//On completion clear the status
				//status.text('');
                $('#uploadResult').html(response)
				//Add uploaded file to list

			}
		});
	}); */
	
