var PostNewItem   = new Object();
var Functions   = new Object();
var Store   = new Object();
//----------------------------------------------------------------//
var UtilLocal =  {
    alertWindowHeight: 200,

    launchModalWindow: function(id) {
        //Get the screen height and width
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();

        //Set heigth and width to mask to fill up the whole screen
        $('#mask').css({'width':maskWidth,'height':maskHeight});

        //transition effect
        $('#mask').fadeIn(1000);
        $('#mask').fadeTo("slow",0.8);

        //Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();

        //Set the popup window to center
        $(id).css('top',  winH/2-$(id).height());
        $(id).css('left', winW/2-$(id).width()/2);

        //transition effect
        $(id).fadeIn(2000);
    },

//    equalheightColumns: function(){
//        var col1_height = $('#col1WrapMiddle').height();
//        var col2_height = $('#col2WrapMiddle').height();
//        var col3_height = $('#wrapMiddle').height();
//
//        $('#col1WrapMiddle').height('auto');
//        $('#col2WrapMiddle').height('auto');
//        $('#wrapMiddle').height('auto');
//
//        if(col1_height > 500 || col2_height > 500 || col3_height > 500){
//            if(col3_height > col2_height && col3_height > col1_height){alert(1);
//                $('#col1WrapMiddle').height(col3_height);
//                $('#col2WrapMiddle').height(col3_height);
//            } else if(col1_height > col2_height && col1_height > col3_height){alert(2);
//                $('#col2WrapMiddle').height(col1_height);
//                $('#wrapMiddle').height(col1_height);
//            } else if(col2_height > col1_height && col2_height > col3_height){alert(3);
//                $('#col1WrapMiddle').height(col2_height);
//                $('#wrapMiddle').height(col2_height);
//            }
//        }
//    },

    equalHeight: function (group) {
        var tallest = 0;
        group.each(function() {
            var thisHeight = $(this).height();
            if(thisHeight > tallest) {
                tallest = thisHeight;
            }
        });
        group.height(tallest);
    }
}
var Util = $.extend(Util, UtilLocal);
//----------------------------------------------------------------//
var BasketLocal = {
    miniCartTopOffset: -17,
    miniCartLeftOffset: 12,
    addToBasket: function(e) {
        e.preventDefault();
        var url = "/index.php?_room=basket&_spAction=addToBasket&room=&showHTML=0" ;
        var product_id = $('a.addToBasket').attr('product_id');
        var link = $('a.addToBasket').attr('link');

        var data = {'product_id': product_id};
        $.post(url, data, function (json) {
            if (json.status == 'error') {
                Util.alert(json.errorMsg);
                return;
            }
            //Util.alert(json.html);
            var count = parseInt(json.count) + 0; //convert to number
            var countText = count + ' ITEM';
            if (count > 1) {
                countText = count + ' ITEMS';
            }

            $("a span.shoppingBagCount").html("(" + countText + ")");
            document.location = link;
            //---------------------//
            //$("#miniCart").html(json.miniCart);
            //Basket.showMiniCart.call($('a.miniCartLink'));
            //------------------//
            
            //setTimeout(function() {
            //    $('#miniCart').slideUp();
            //}, 4000);

        }, 'json');
    }
}

var Basket = $.extend(Basket, BasketLocal);

//=====================================================//
var Validate = $.extend(Validate, {

});

//=====================================================//
var Product = {
    setupJqZoom: function() {
        $('.product .detailCont .pictureContainer img').each(function(i){
            var imgUrl = $(this).attr('src');
            imgUrl = imgUrl.replace(/normal\//, "large/");
            $(this).parent().attr('href', imgUrl);
        });

        var options = {
            zoomWidth: 250,
            zoomHeight: 250,
            xOffset: 10,
            yOffset: 0,
            position: 'left',
            title: false
        };
        $('.product .detailCont .pictureContainer a.zoomImage').jqzoom(options);
    },

    setupImageSlider: function() {
        var paused = false;
        var pausedByHover = false;
        setSlideshowControl();
        //$(document).everyTime(3000, function() {
        //    slideSwitch();
        //});

        $('#slideshow img').each(function(i){
            var imgUrl = $(this).attr('src');
            imgUrl = imgUrl.replace(/normal\//, "large/");
            $(this).parent().attr('href', imgUrl);
        });

        // $('#slideshow').hover(
        //     function(){
        //         if (!paused) {
        //             pauseSlideshow();
        //             pausedByHover = true;
        //         }
        //     },
        //     function(){
        //         if (pausedByHover) {
        //             playSlideshow(false);
        //         }
        //         pausedByHover = false;
        //     }
        // );

        //set the slideshow controls handlers
        $('#slideshowControl img.pause')
        .click(function() {
            pauseSlideshow();
        });
        $('#slideshowControl img.play')
        .click(function() {
            playSlideshow();
        });
        $('#slideshowControl img.forward')
        .click(function() {
            slideSwitch();
        });

        function slideSwitch() {
            var $active = $('#slideshow div.active');
            if ($active.length == 0) {
                $active = $('#slideshow div:last');
            }

            var $next = $active.next().length ? $active.next() : $('#slideshow div:first');
            $active.addClass('last-active');

            $next
            .css({opacity: 0.0})
            .addClass('active')
            .animate({opacity: 1.0}, 1000, function() {
                $active.removeClass('active last-active');
            });
        }

        function setSlideshowControl() {
            $('#slideshowControl img').hide();
            if (paused) {
                $('#slideshowControl img.play').show();
                $('#slideshowControl img.forward').show();
            } else {
                $('#slideshowControl img.pause').show();
            }
        }

        function pauseSlideshow(setControls) {
            setControls = setControls == undefined ? true : setControls;
            paused = true;
            if (setControls) {
                setSlideshowControl();
            }
            $(document).stopTime();

        }

        function playSlideshow() {
            paused = false;
            setSlideshowControl();
            // $(document).everyTime(3000, function(i) {
            //     slideSwitch(i);
            // });
        }


    },

    setValuesByMake: function() {
        var make   = $("select#make").val();

        if(make == ''){
            $("select#year").val('').attr("disabled", true);
            $("select#model").val('').attr("disabled", true);
            $("select#type").val('').attr("disabled", true);
        } else {
            $("select#year").val('').attr("disabled", false);
            $("select#model").val('').attr("disabled", false);
            $("select#type").val('').attr("disabled", false);

            var url = "/index.php?_room=product&_spAction=carsJson&showHTML=0&fld_name=year";
            $("select#year").removeOption(/./).ajaxAddOption(url, {make : make}, false);

            var url = "/index.php?_room=product&_spAction=carsJson&showHTML=0&fld_name=model";
            $("select#model").removeOption(/./).ajaxAddOption(url, {make : make}, false);

            var url = "/index.php?_room=product&_spAction=carsJson&showHTML=0&fld_name=type";
            $("select#type").removeOption(/./).ajaxAddOption(url, {make : make}, false);

        }
    },

    setValuesByYear: function() {
        var make   = $("select#make").val();
        var year   = $("select#year").val();

        var url = "/index.php?_room=product&_spAction=carsJson&showHTML=0&fld_name=model";
        $("select#model").removeOption(/./).ajaxAddOption(url, {make : make, year: year}, false);

        var url = "/index.php?_room=product&_spAction=carsJson&showHTML=0&fld_name=type";
        $("select#type").removeOption(/./).ajaxAddOption(url, {'make' : make, year: year}, false);
    },

    setValuesByModel: function() {
        var make   = $("select#make").val();
        var year   = $("select#year").val();
        var model  = $("select#model").val();

        var url = "/index.php?_room=product&_spAction=carsJson&showHTML=0&fld_name=type";
        $("select#type").removeOption(/./).ajaxAddOption(url, {'make' : make, year: year, model: model}, false);
    }
}


//=====================================================//
var Member = {
    setupRegisterForm: function(e) {
        /*var extraPar = {
            callback: function() {
                var msg =
                "<div>" +
                "Thank you for registering with Poshpile. An email confirmation of your account has been sent to you.<br/><br/>" +

                "Please click continue shopping to go back to the product pages.<br/><br/>" +

                "The Posh Pile team" +
                "</div>" +

                "<div style='margin-top:110px; text-align:center;'>" +
                "<a href='/shop/'><img src='/images/continue_shopping.jpg' /></a>" +
                "</div>";
                $('#registerForm').html(msg);
            }
        }*/

        var extraPar = {
            callback: function() {
                var url = '/index.php?_room=member&_spAction=newMemberThanks&showHTML=0';
                $.get(url, function (data) {
                    $('#registerForm').html(data);
                })
            }
        }

        var options = {
            success: function(json, statusText, jqFormObj) {
                Validate.validateFormData(json, statusText, jqFormObj, extraPar);
                $('#wrapMiddle').height('auto');
                Util.equalHeight($('.equalColumn'));
                Util.hideProgressInd();
            },
            beforeSubmit: function() {
                Util.showProgressInd();
            },
            dataType: 'json'
        };
        $('#registerForm').ajaxForm(options);
    },

    setupEditProfileFormForm: function(e) {
        var extraPar = {
            callback: function() {
                var msg = "<div class='sysMessage'>Your profile has been updated.</div>";
                $('#editProfileForm').html(msg);
            }
        }

        var options = {
            success: function(json, statusText, jqFormObj) {
                Validate.validateFormData(json, statusText, jqFormObj, extraPar);
            },
            beforeSubmit: function() {},
            dataType: 'json'
        };
        $('#editProfileForm').ajaxForm(options);
    },

    setupChangePasswordForm: function(e) {
        var extraPar = {
            callback: function() {
                var url = '/index.php?_room=member&_spAction=changePasswordThanks&showHTML=0';
                $.get(url, function (data) {
                    $('#changePasswordForm').html(data);
                })
            }
        }

        var options = {
            success: function(json, statusText, jqFormObj) {
                Validate.validateFormData(json, statusText, jqFormObj, extraPar);
            },
            beforeSubmit: function() {},
            dataType: 'json'
        };
        $('#changePasswordForm').ajaxForm(options);
    }
}


var Dialog = {

    setUpForm: function(formName) {
        $('#' + formName).livequery(function() {

            /****************************************************/
            var extraPar = {
                callback: function(json) {
                    if (json.returnText != ''){
                    	$('#dialog').dialog('destroy');
                        Util.showSimpleMessageInDialog(json.returnText);
                    }
                }
            }

            var options = {
                success: function(json, statusText, jqFormObj) {
                    Validate.validateFormData(json, statusText, jqFormObj, extraPar);
                    Util.hideProgressInd();
                },
                beforeSubmit: function(frmData) {
                    Util.showProgressInd();
                },
                dataType: 'json'
            };

            $('#' + formName).ajaxForm(options);

        });
    },

    openDialog: function(formName, dialogTitle) {

        url = $(this).attr('href');

        Util.showProgressInd();

        $.get(url, function(data){
            Util.initDialog();
            $('#dialog').html(data);

            var xButtons = {};

            xButtons[Lang.data.submit] = function() {
                $('#' + formName).submit();
            };

            xButtons[Lang.data.cancel] = function() {
                $(this).dialog('close');
                $(this).dialog('destroy');
            };

            var x_dialog = $('#dialog').dialog(
                $.extend(Util.dialogDefaults, {
                    width: 400,
                    height: 250,
                    title: dialogTitle,
                    buttons: xButtons
                })
            );
            Util.hideProgressInd();
        });
    }

}

Store = {
    mapSearchFormSubmit: function(no_post_code_msg){
        if($('#address_po_code').val() == ''){
            Util.alert(no_post_code_msg);
        } else {
            $('#mapSearchForm').submit();
        }
    },
    
    drawMarkers: function(centerLat, centerLng, json){
        var centerLatLng = new google.maps.LatLng(centerLat, centerLng);
        var mapOptions = {
          zoom: 4,
          center: centerLatLng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };   
        
        Store.mapObj = new google.maps.Map(document.getElementById("storesMap"), mapOptions);         
        if(json.centerLat && json.centerLng){
            centerLatLng = new google.maps.LatLng(json.centerLat, json.centerLng);
            Store.mapObj.setCenter(centerLatLng);
            Store.mapObj.setZoom(10);
        }
        var i = 0;
        Store.marker = new Array();
        Store.infowindow = new Array();
        Store.lastOpenInfoWindow = null;
        if(json.hasError){
            Util.alert(json.errorMsg);
            return;
        }
        $.each(json.result, function() {
            var latlng = new google.maps.LatLng(this.lat, this.lng);
            
            var marker = new google.maps.Marker({
               map:Store.mapObj
               ,position: latlng
            });      

            
            var infowindow = new google.maps.InfoWindow({
                 maxWidth: 200
                ,content: this.html
            });
            
            Store.marker[i] = marker;
            Store.infowindow[i] = infowindow;
            
            google.maps.event.addListener(marker, 'click', function() {
                if(Store.lastOpenInfoWindow != null){
                    Store.lastOpenInfoWindow.close();
                }
                infowindow.open(Store.mapObj, marker);
                Store.lastOpenInfoWindow = infowindow;
            });    
            
            var openInfoFromOutside = "<a class='showOnMap' href='javascript:void(0);' onclick=\"Store.openInfoWindowFromOutside(" + i + ")\"><span>Show On Map</span></a>";
            $('#storesListFromJson').append(this.html + openInfoFromOutside);
            
            i++;

        });
    
    },
    
    openInfoWindowFromOutside: function(count) {
        if(Store.lastOpenInfoWindow != null){
            Store.lastOpenInfoWindow.close();
        }        
        Store.infowindow[count].open(Store.mapObj, Store.marker[count]);
        Store.lastOpenInfoWindow = Store.infowindow[count];
    }
}

