/**
 * Logging if possible
 */
var COOLDEALS = {};

COOLDEALS.Util = {
    reload : function() {
        location.replace(location.href.replace(/\?.*$/, '') + '?' + Math.random());
    }
};

/**
 * Coundown
 */
COOLDEALS.CountDown = function(secElem, minElem, hourElem) {
    this.secDiv = $(secElem);
    this.minDiv = $(minElem);
    this.hoursDiv = $(hourElem);
    this.seconds = parseInt(this.secDiv.html(), 10);
    this.minutes = parseInt(this.minDiv.html(), 10);
    this.hours = parseInt(this.hoursDiv.html(), 10);

    this.display = function(secElem, minElem, hourElem, seconds, minutes, hours) {
        $(secElem).html((seconds + '').length < 2 ? '0' + seconds : seconds);
        $(minElem).html((minutes + '').length < 2 ? '0' + minutes : minutes);
        $(hourElem).html((hours + '').length < 2 ? '0' + hours : hours);
    };

    this.down = function(secElem, minElem, hourElem) {
    	var secDiv = $(secElem);
        var minDiv = $(minElem);
        var hoursDiv = $(hourElem);
        for (i=0 ; i<$(secDiv).size() ; i++) {
	        var seconds = parseInt($($(secDiv)[i]).html(), 10);
	        var minutes = parseInt($($(minDiv)[i]).html(), 10);
	        var hours = parseInt($($(hoursDiv)[i]).html(), 10);
	        if (!(hours == 0 && minutes == 0 && seconds == 0)) {
	            seconds--;
	            if (seconds < 0) {
	                seconds = 59;
	                minutes--;
	                if (minutes < 0) {
	                    minutes = 59;
	                    hours--;
	                }
	            }
	            this.display($(secDiv)[i], $(minDiv)[i], $(hoursDiv)[i], seconds, minutes, hours);
	        }
	        else {
	            this.display($(secDiv)[i], $(minDiv)[i], $(hoursDiv)[i], seconds, minutes, hours);
	           // window.setTimeout(COOLDEALS.Util.reload, (Math.floor(Math.random()*21000)+5000));
	        }
        }
    };
};

COOLDEALS.spinner = {
    show : function($parentElem) {
        $parentElem.append('<img src=' + 'window.location.host' + '/images/default/spinner.gif" width="15" height="15" alt="loading" id="ajax-spinner" />');
        //$parentElem.append('<img src="http://localhost/cooldeals/images/default/spinner.gif" width="15" height="15" alt="loading" id="ajax-spinner" />');
    },
    remove : function() {
        $('#ajax-spinner').remove();
    }
};

COOLDEALS.ExponentialBackoff = function(start, max) {
    this.clear = function() {
        this.current = start;
        this.max = max;
    };
    this.clear();
    this.getNext = function() {
        var waitTime = this.current;
        if (this.current < this.max) {
            this.current *= 2;
        }
        return waitTime;
    };
};

COOLDEALS.DealCounterPolling = function(counterElem, reqUrl, highlightElem) {

    window.setTimeout(poll, 1000);

    var INTERVALS = 4,
            INTERVAL_LBOUND = 300,
            INTERVAL_UBOUND = 1000,
            $counterElem = $(counterElem),
            $highlightElem = $(highlightElem),
            counterVal = parseInt($counterElem.html(), 10),
            RETRY = new COOLDEALS.ExponentialBackoff(1000, 128000);

    function poll() {
        $.jsonp({
            url: reqUrl,
            callback: "jsonpCallback",
            success: function(json) {
                if (json.c) {
                    handleUpdate(json.c);
                }
                window.setTimeout(poll, 100);
                RETRY.clear();
            },
            error: function(xOptions, textStatus) {
                if (textStatus == 'timeout') {
                    window.setTimeout(poll, 100);
                }
                else if (textStatus == 'error') {
                    var retry = RETRY.getNext();
                    window.setTimeout(poll, retry);
                }
            }
        });
    }

    function handleUpdate(amount) {
        var diff = amount - counterVal || 1,
                remainder = diff % INTERVALS,
                incr = parseInt(diff / INTERVALS, 10),
                timekeeper = 10;
        for (var i = 0; i < INTERVALS; i++) {
            var incrBy = (i == 0) ? incr + remainder : incr;
            window.setTimeout(function(j) {
                return function() {
                    updateCounter(j)
                }
            }(incrBy), timekeeper);
            if (incr == 0) {
                break;
            }
            timekeeper += Math.floor(Math.random() * (INTERVAL_UBOUND - INTERVAL_LBOUND) + INTERVAL_LBOUND);
        }
    }

    function updateCounter(amount) {
        counterVal += amount;
        $counterElem = $(counterElem).html(counterVal);
        $highlightElem.effect("highlight", {}, INTERVAL_LBOUND);
    }

};

COOLDEALS.EditMyDataInPlace = function(formWrapper, sectionClass, editClass, saveClass, cancelClass) {

    var s = formWrapper + sectionClass;

    var options = {
        beforeSubmit: beforeSubmit,
        success: handleSuccess,
        error: handleError
    };

    $(formWrapper).find('form').each(function() {
        $(this).validate({
            submitHandler: function(form) {
                $(form).ajaxSubmit(options);
                return false;
            }
        })
    });

    $(s + editClass).click(function(event) {
        var $target = $(event.target);
        if (!$target.hasClass('addForm')) {
            var elem = $target.parents(s);
            elem.addClass('inactive');
            var editElem = $('#' + elem.attr('id') + '-edit');
            editElem.removeClass('inactive');
        }
        else {
            $target.hide();
            $target.siblings('.addForm-hidden').show();
        }
    }
            );

    $(s + cancelClass).click(function(event) {
        var elem = $(event.target).parents('form');
        closeEdit(elem);
    });

    function closeEdit($form, highlight) {
        if ($form.hasClass("addForm-hidden")) {
            $form.siblings('.addForm').show();
            $form.hide()
        }
        else {
            var $elem = $form.parents(s);
            $elem.addClass('inactive');
            var showElem = $('#' + $elem.attr('id').replace('-edit', ''));
            showElem.removeClass('inactive');
            if (highlight) {
                showElem.effect("highlight", {}, 1000);
            }
        }
    }

    function beforeSubmit(arr, $form, options) {
        COOLDEALS.spinner.show($form);
    }

    function handleSuccess(responseText, statusText, xhr, $form) {

        if (responseText.success) {

            COOLDEALS.spinner.remove();

            if ($form) {
                var elem = $form.parents(s),
                        showElem = $('#' + elem.attr('id').replace('-edit', ''));

                // update all fields that have class update
                $form.find('.update').each(function() {
                    var lookfor = $(this).attr('name'),
                            value = $(this).attr('tagName') == 'SELECT' ? $(this).find(':selected').text() : $(this).val();
                    $(showElem).find('#update-' + lookfor).html(value);
                });

                closeEdit($form, true);
            }

            if (responseText.reload) {
                window.location.search = '?tab=mydata&lang=' + responseText.reload;
            }

            if (responseText.subscriptions) {
                $('.main-account-content-data-box-section-edit-cities-list').html(responseText.subscriptions);
            }

        }
        else {
            closeEdit($form.parents(s), false);

        }

    }

    function handleError() {
        COOLDEALS.spinner.remove();
    }

    $('.main-account-content-data-box-cross').live('click', function(event) {

        var city = parseInt($(event.target).attr('id').match(/\d+$/), 10);

        $.ajax({
            type: 'post',
            data:  {type: 'DELETE', dealcity: city },
            url: $('#cities-edit').attr('action'),
            dataType: 'json',
            success: handleSuccess,
            error: handleError
        });
    });
};

COOLDEALS.DropDown = function(trigger, dropElem) {
    var expanded = false;
    for (var i = 0; i < trigger.length; i++) {
        $(trigger[i]).click(function(event) {
            if (!this.dropElem) {
                this.dropElem = $(dropElem)
            }
            if (expanded) {
                expanded = false;
                this.dropElem.slideUp();
            }
            else {
                expanded = true;
                this.dropElem.slideDown();
            }
        })
    }
};

COOLDEALS.LanguageSwitch = function(container, langElem, langVal) {
    var $container = $(container);

    $container.find(langElem).each(function() {
        if (!$(this).hasClass('current')) {
            $(this).click(function() {
                var lang = $(this).attr('id').match(langVal)[1];
                window.location.search = '?lang=' + lang;
            });
        }
    });

};

COOLDEALS.signupForm = {

    theBox : function() {
        return this._box ? this._box : (this._box = $('#welcomeBox'));
    },

    initialForm : function() {
        return this._initial ? this._initial : (this._initial = this.theBox().html());
    },

    isOverlay : false,

    closeOverlay : function() {
        this.theBox().jqmHide();
    },

    stepForms : ['welcomeForm', 'registerForm', 'contactsForm', 'inviteForm'],

    decide : function(result) {
        var $result = $(result);
        for (var i in this.stepForms) {
            var form = this.stepForms[i];
            if ($result.attr('id') == form || $result.find('#' + form).size()) {
                this[form].call(this, result);
                break;
            }
        }
    },

    submit :  function(form) {
        var $form = $(form),
                params = $form.serialize(),
                that = this;
        $.post(
                $form.attr('action'),
                params,
              function(result) {
                  that.decide(result);
              }
                );
    },

    startWelcomeOverlay : function() {
        var that = this;
        this.initialForm();
        this.theBox().jqm({modal:true, toTop:true}).jqmShow();
        this.isOverlay = true;
        $('a.closeOverlay').live('click', function() {
            that.closeOverlay()
        });
        this.welcomeForm();
    },

    startContactsEmbedded : function() {
        var that = this;
        this.initialForm();
        this.theBox().find('#contactsForm').validate({
            submitHandler: function(form) {
                that.submit(form);
            }
        });
    },

    welcomeForm : function() {
        var that = this;
        this.theBox().find('#welcomeForm').validate({
            submitHandler: function(form) {
                that.submit(form);
            }
        });
    },

    registerForm : function(result) {
        this.theBox().html(result);
        var that = this;
        this.theBox().find('#registerForm').validate({
            submitHandler: function(form) {
                that.submit(form);
            }
        });
    },

    contactsForm : function(result) {
        this.theBox().html(result);
        var that = this;
        this.theBox().find('#contactsForm').validate({
            submitHandler: function(form) {
                that.submit(form);
            }
        });
    },

    inviteForm : function(result) {
        this.theBox().html(result);
        var that = this;
        this.theBox().find('#inviteForm').validate({
            submitHandler: function(form) {
                that.processInvite(form);
            }
        });
    },

    processInvite : function(form) {
        var $form = $(form),
                params = $form.serialize(),
                that = this;
        $.post(
                $form.attr('action'),
                params,
              function(result) {
                  $('#main').before($('#ifSuccess').html());
                  if (that.isOverlay) {
                      that.closeOverlay()
                  }
                  that.theBox().html(that.initialForm());
              }
                );
    }

};

COOLDEALS.CheckoutChange = function(checkoutForm, amountElem, method, orderButton, promoCodeBtn, deliverySpeed) {
    $(amountElem).add(method).change(function() {
        var location = window.location.href;
        reloadForm(location);
    });
    
    $(promoCodeBtn).click(function() {
        var location = window.location.href;
        reloadForm(location);
    });
    
    $(deliverySpeed).click(function() {
        var location = window.location.href;
        reloadForm(location);
    });

    function reloadForm(location) {
        var $checkoutForm = $(checkoutForm);
        $checkoutForm.find('input:hidden[name=qty]').val($(amountElem).val());
        $(orderButton).hide();
        $checkoutForm.unbind('submit');
        $checkoutForm.attr('action', location).submit();
    }
};

COOLDEALS.PaymentMethodDropDown = function(triggerElem, dropDownClass) {
    $(triggerElem).click(function() {
        $(".payment-dropdown").hide();
        var showElem = "#payment-dropdown-" + $(this).attr("id");
        $(showElem).show();
    });
};

COOLDEALS.startup = {
    // Counter
    initDealCounter : function() {
        var secElem = ".remaining-seconds",
                minElem = ".remaining-minutes",
                hourElem = ".remaining-hours";
        var myCountdown = new COOLDEALS.CountDown(secElem, minElem, hourElem);
        window.setInterval(function() {
            myCountdown.down(secElem, minElem, hourElem)
        }, 1000);
    },

    // Update Bought
    initDealAmount : function() {
        /*
         var counter = "#totalPurchases",
         baseUrl = decodeURIComponent($('#totalPurchases').attr('class')),
         highlight = '.main-deal-sidebar-box-shop-amount';
         COOLDEALS.COUNTER = new COOLDEALS.DealCounterPolling(counter, baseUrl, highlight);
         */
    },

    // Signup and Contact Import
    initSignup : function() {
        if ($('.startWelcomeOverlay').size()) COOLDEALS.signupForm.startWelcomeOverlay();
        if ($('.startContactsEmbedded').size()) COOLDEALS.signupForm.startContactsEmbedded();
    },

    // Cities and Email Dropdown
    initTopDropdown : function() {
        var triggerCity = ["#header-top-deal-city-container-name", "#header-top-more-cities-text", "#drop-down-container-close-city"],
                dropCity = "#drop",
                triggerEmail = ["#header-top-deal-alerts-text", "#drop-down-container-close-email"],
                dropEmail = "#drop-email";
        new COOLDEALS.DropDown(triggerCity, dropCity);
        new COOLDEALS.DropDown(triggerEmail, dropEmail);
    },

    //Checkout Dropdown
    initCheckoutDropdown : function() {
        var triggerLogin = ["#checkout-login-button-container"],
            dropLogin = "#drop-login",
            triggerRegister = ["#checkout-register-button-container"],
            dropRegister = "#drop-register";
        new COOLDEALS.DropDown(triggerLogin, dropLogin);
        new COOLDEALS.DropDown(triggerRegister, dropRegister);
    },

    // Account My Data Edit in Place
    initMyAccountMyData : function() {
        var formWrapper = ".main-account-content-data-box",
                sectionClass = "-section",
                editClass = "-edit",
                saveClass = '-save',
                cancelClass = '-cancel';
        new COOLDEALS.EditMyDataInPlace(formWrapper, sectionClass, editClass, saveClass, cancelClass);
    },

    // RegistrationLanding Form Validation
    initRegistrationLanding: function() {
        $('#registrationLanding').validate();
    },

    // Registration Promo Form Validation
    initRegisterWelcomeValidate: function() {

        $('#registerForm').validate({
            rules: {
                passconfirm: {
                    equalTo: "#password"
                }
            }
        });
    },

    // Register Form Validation
    initRegistrationForm: function() {
        $('#registration').validate();
    },

    // Login Form Validation
    initLoginForm: function() {
        $('#loginForm').validate();
    },

    // Top Email Subscription Form Validation
    initEmailSubscription: function() {
        $('#subscriptionDrop').validate();
    },

    // Language Selector
    initLanguageSelect : function() {
        var container = '#languageSwitch',
                langElem = '.locale',
                langVal = /lang-(\w*$)/;
        new COOLDEALS.LanguageSwitch(container, langElem, langVal);
    },

    // Checkout Amount Select Update
    initCheckout : function() {
        var checkoutForm = '#checkout',
                amountElem = "#qty",
                method = 'input:radio[name=method]',
                orderButton = '.main-left-col-login-form-submit-payment',
                paymentHash = '#payment',
                hashRegex = /\#payment/,
                promoCodeBtn = '#promo-code-btn',
                deliverySpeed = '.deliverySpeed';

        new COOLDEALS.CheckoutChange(checkoutForm, amountElem, method, orderButton, promoCodeBtn, deliverySpeed, paymentHash, hashRegex);

        var triggerElem = ".radio-style-payment",
                dropDownClass = ".payment-dropdown";
        new COOLDEALS.PaymentMethodDropDown(triggerElem, dropDownClass);

        $(checkoutForm).validate();
    },

    // Checkout auto redirect
    initCheckoutRedirect : function() {
        var paymentForm = $("#paymentForm");
        paymentForm.submit();
    },

    // Facebook Javascript SDK
    initFacebookJsSdk : function() {
        if (!document.getElementById('fb-root') || !jQuery.support.scriptEval) {
            return;
        }
        window.fbAsyncInit = function() {
            var appId = $('meta[property=fb:app_id]').attr("content") || "103048633083639";
            FB.init({appId: appId, status: true, cookie: true});
            FB.XFBML.parse();
        };
        $.getScript(document.location.protocol + '//connect.facebook.net/en_US/all.js');
    },

    // Twitter Widget
    initTwitterWidget : function() {
        if (!document.getElementById('tw-root')) {
            return;
        }
        $.getScript(document.location.protocol + '//widgets.twimg.com/j/2/widget.js', function() {
            var user = $('#twitterUser').html();
            new TWTR.Widget({
                id : 'tw-root',
                version: 2,
                type: 'profile',
                rpp: 3,
                interval: 6000,
                width: 217,
                height: 250,
                theme: {
                    shell: {
                        background: '#fcfcfc',
                        color: '#333'
                    },
                    tweets: {
                        background: '#ffffff',
                        color: '#333',
                        links: '#2D4D93'
                    }
                },
                features: {
                    scrollbar: false,
                    loop: false,
                    live: true,
                    hashtags: true,
                    timestamp: true,
                    avatars: false,
                    behavior: 'all'
                }
            }).render().setUser(user).start();
        });
    },

    //Twitter Share
    initTwitterShare: function() {
        $.getScript(document.location.protocol + '//platform.twitter.com/widgets.js');
    }

};

COOLDEALS.init = function() {
    var c = document.getElementById('body').className.split(' '), d;
    for (var i = 0; i < c.length; i++) {
        if (d = c[i].match(/(?:^js-)(.*)/)) {
            if (d = d[1]) {
                if (typeof COOLDEALS.startup["init" + d] == 'function') {
                    COOLDEALS.startup["init" + d]()
                }
            }
        }
    }
};

/**
 * Init
 */
$(document).ready(function() {
    COOLDEALS.init();

    jQuery.validator.addMethod("lettersOnly", function(value, element) {
        return this.optional(element) || /^[a-z-.,\s]+$/i.test(value);
    }, "Letters only please");
    
    jQuery('.numbersOnly').keyup(function () { 
        this.value = this.value.replace(/[^0-9\.]/g,'');
    });
    
});


function populateCityAndCallingCode(_url, _url2, _url3, city, callingCode, area, deliverySpeed){
	var cc = $('#country').val();
	$.ajax({
		url:_url,
		dataType: 'json',
		data: {
			id: cc
		},
		success: function(data) {
			
			var cityOptions = '' ;
			$.each(data.cities,function(_cityId,_city) {
				cityOptions += '<option value="' + _cityId + '">' + _city+ '</option>'; 
				//alert(_cityId + " - " + _city);
			});
			$("#city").html(cityOptions);
			var cityVal = city;
			
			if (cityVal != '') {
				$('#city').val(cityVal) ;
			}
			
			var callingCodeOptions = '' ;
			$.each(data.callingcodes,function(_callingCodeId,_callingCode) {
				$("#callingCode").empty().append("Loading Codes..");
				callingCodeOptions += '<option value="' + _callingCodeId + '">' + _callingCode+ '</option>'; 
				//alert(_callingCodeId + " - " + _callingCode);
			});
			$("#callingCode").html(callingCodeOptions);
			var callingCodeVal = callingCode;
			if (callingCodeVal != '') {
				$('#callingCode').val(callingCodeVal) ;
			}
			populateCityAreas(_url2, area);
			populateDeliverySpeed(_url3, deliverySpeed);
		},
		error: function(request, status, error) {
			alert(request)
			alert(error)
		}
		
	});
}

function populateCityAreas(_url, area){
	var cc = $('#city').val();
	$.ajax({
		url:_url,
		dataType: 'json',
		data: {
			id: cc
		},
		success: function(data) {
			var areaOptions = '' ;
			$.each(data,function(_areaId,_area) {
				areaOptions += '<option value="' + _areaId + '">' + _area+ '</option>'; 
			});
			$("#area").html(areaOptions);
			var areaVal = area;
			if (areaVal != '') {
				$('#area').val(areaVal) ;
			}
			
			
		},
		error: function(request, status, error) {
			alert('err populateCityAreas');
			alert(request)
			alert(error)
		}
	});
}

function populateDeliverySpeed(_url, deliverySpeed){
	var cc = $('#city').val();
	$.ajax({
		url:_url,
		data: {
			id: cc
		},
		success: function(data) {
			$("#dev-delivery-speed").html(data)		
			COOLDEALS.startup["initCheckout"]()
			if (deliverySpeed != '') {
				$('#deliverySpeed'+deliverySpeed).attr('checked', true);
			}
		},
		error: function(request, status, error) {
			alert('err populateCityAreas');
			alert(request)
			alert(error)
		}
	});
}
