﻿$.fn.popup = function (options) {
    var __ele = $(this);
    opts = $.extend({
        closeBtn: '.close',
        onClose: function () {
        },
        onShow: function () {
        }
    }, options || {});

    $(opts.closeBtn).click(function () {
        close();
        return false;
    });

    var _mask = $('<div></div>');
    $(_mask).css("background", "#000000")
                   .css("filter", "alpha(opacity=0.5)")
                   .css("opacity", "0.5")
                   .css("width", "100%")
                   .css("height", $(document).height() + "px")
                   .css("position", "absolute")
                   .css("left", "0px")
                   .css("top", "0px")
                   .css("z-index", "9998");
    $('body').append(_mask);

    $(__ele).css("display", "block");

    function redraw() {
        var dw = $("body").width();
        var dh = $(document).height();
        var wh = $(window).height();
        var st = $('body')[0].scrollTop;
        var w = $(__ele).width();
        var h = $(__ele).height();
        $(__ele).css("left", (dw - w) / 2 + "px")
                    .css("top", (wh - h) / 2 + st + "px")
                    .css("position", "absolute")
                    .css("z-index", "9999");

        $(_mask).css("width", "100%")
                    .css("z-index", "9998")
                    .css("height", $(document).height() + "px")
    }

    function close() {
        $(_mask).remove();
        $(__ele).css("display", "none");
        if ((typeof opts.onClose) == 'function') opts.onClose();
    }
    $(window).resize(function () {
        redraw();
    });
    redraw();
    if ((typeof opts.onShow) == 'function') {
        opts.onShow();
    }
};

$.fn.tipText = function (opts) {
        var __ele = $(this);
        opts = $.extend({
            tipAttr: 'tipText',
            tipColor: '#cccccc',
            defaultColor: '#000000',
            form:null
        }, opts || {});

        $(opts.form).submit(function(){
            if($(__ele).val() == $(__ele).attr(opts.tipAttr)){
                $(__ele).val('');
            }
        });

        $(__ele).blur(function () {
            if ($.trim($(this).val()).length == 0 || $(this).val() == $(this).attr(opts.tipAttr)) {
                with ($(this)) {
                    css('color', opts.tipColor);
                    val(attr(opts.tipAttr));
                }
            } else {
                $(this).css('color', opts.defaultColor);
            }
        });

        $(__ele).focus(function () {
            $(this).css('color', opts.defaultColor);
            if ($.trim($(this).val()).length == 0 || $(this).val() == $(this).attr(opts.tipAttr)) {
                $(this).val('');
            }
        });

        $(__ele).blur();
};


$.fn.mapTree=function(opts){
    var __ele = $(this);
    opts = $.extend({
        showOneSubTree: true,
        expandAll:true,
        expandFirst:true
    }, opts || {});

    $(__ele).find(' > li > dl > dt > span').click(function(){
        collapseOrExpand($(this).parent());
    });

    $(__ele).find(' > li > dl input[type="checkbox"]').click(function(){
        checked($(this));
    });
        
    function collapseOrExpand(el){
        if($(el).parent().find('dd').css('display')!='none'){
            collapse(el);
        }else{
            expand(el);
        }
    }

    function expand(el){
        if(opts.showOneSubTree){
            $(__ele).find(' > li > dl > dt').each(function(){
                if($(el).html()!=$(this).html()){
                    collapse(this);
                }else{
                    $(this).parent().find('dd').css('display','block');
                    $(this).find('>span:first').text('-');
                }
            });
        }else{
            $(el).find('>span:first').text('-');
            $(el).parent().find('dd').css('display','block');
        }
    }

    function collapse(el){
        $(el).find('>span:first').text('+');
        $(el).parent().find('dd').css('display','none');
    }

    function checked(checkbox){
        var v=$(checkbox).attr('checked');
        if($(checkbox).parent().attr('tagName').toLowerCase()=='dt'){
            with($(checkbox).parent().parent().find('>dd>input[type="checkbox"]')){
                if(!v){
                    removeAttr('checked');
                }else{
                    attr('checked','checked');
                }
            }
            expand($(checkbox).parent());
        }else if($(checkbox).parent().attr('tagName').toLowerCase()=='dd'){
            var checkLength=$(checkbox).parent().parent().find('>dd>input[type="checkbox"]:checked').length;
            var count=$(checkbox).parent().parent().find('>dd>input[type="checkbox"]').length;
            with($(checkbox).parent().parent().find('>dt:first>input[type="checkbox"]')){
                if(checkLength!=count){
                    removeAttr('checked');
                }else{
                    attr('checked','checked');
                }
            }
        }
    }

    $(__ele).find(' > li > dl > dt').each(function(){
        if(opts.expandAll){
            expand(this);
        }else{
            collapse(this);
        }
    });

    if(opts.expandFirst){
        expand($(__ele).find(' > li:first > dl > dt'));
    }

};

function googleMap(container,address,vendors,resourceUrl,icon) {  
    var __bounds= new GLatLngBounds();  
     if (GBrowserIsCompatible()) {  

     var map = new GMap2(container);  
     map.addControl(new GSmallMapControl());
     map.addControl(new GScaleControl());

    var geocoder = new GClientGeocoder();  
    geocoder.getLatLng(address,function(point){  
        if (!point)   
        {  
            //alert("not found:"+point);  
        }   
        else   
        {  
            //show point  
            map.setCenter(point, 12);  
            //add note  
            //var marker = new GMarker(point);  
            //map.addOverlay(marker);  
        }  
    });  
    
    var baseIcon = new GIcon();  
    baseIcon.shadow = "http://www.google.cn/mapfiles/shadow50.png";  
    baseIcon.iconSize = new GSize(35, 49);  
    baseIcon.shadowSize = new GSize(37, 34);  
    baseIcon.iconAnchor = new GPoint(9, 34);  
    baseIcon.infoWindowAnchor = new GPoint(9, 2);  
    baseIcon.infoShadowAnchor = new GPoint(18, 25);  
  
    function createMarker(point, index, address) { 
        __bounds.extend(point); 
        var letter = String.fromCharCode("A".charCodeAt(0) + index);  
        var letteredIcon = new GIcon(baseIcon);  
        //letteredIcon.image = "http://www.google.cn/mapfiles/marker" + letter + ".png";  
        letteredIcon.image = resourceUrl+'/type-'+icon+'.png'; 

        markerOptions = { icon:letteredIcon };  

        var marker = new GMarker(point, markerOptions);  
        marker.record=address;
  
        GEvent.addListener(marker, "click", function() {  
        marker.openInfoWindowHtml(GetWindowHtml(marker.record));  
        });  

        try {
            map.setZoom(map.getBoundsZoomLevel(__bounds));
            map.setCenter(__bounds.getCenter());  
        } catch (e) {
            map.setCenter(point, 12);
        }

        return marker;  
    }  

      
    function GetPoint(address,index){  
        var geocoder = new GClientGeocoder();  
            if (geocoder)   
            {  
                geocoder.getLatLng(address.Address,function(point){  
                    if (!point)   
                    {  
                      //alert("not found:"+address);  
                    }   
                    else   
                    {  
                        //标记地址 显示图片  
                        var marker=createMarker(point, index, address);
                        map.addOverlay(marker); 
                        if(vendors){
                            if(vendors.length==1){
                                marker.openInfoWindow(GetWindowHtml(marker.record));
                            }
                        }
                    }  
                });  
            }  
         }  

    function GetWindowHtml(Address){
        var r=Address;
        var s='<div style="width:368px;overflow:hidden;margin:15px auto;">'+
            '	<div style="width:155px;float:left;">'+
            '    	<h4 style="margin:3px 0px;">'+r.Vendor+(r.Logo!=''?' <img src="'+r.Logo+'" width="50" height="23" border="0" align="absmiddle" />':'')+'</h4>'+
            '    	<p style="font-size:14px;margin:0px 0px 3px 0px;">'+r.Address+
            '        </p>'+($.trim(r.Phone).length==0?'':'<P style="font-weight:bold;font-size:14px;margin:0px;">'+r.Phone+'</P>')+
            '        <P style="font-weight:bold;font-size:11px;margin:0px;word-break:break-all;word-break: normal;"><a href="' + r.WebAddressHyperlink + '" target="_blank">' + r.WebAddress +
            '        </a></P>' +
            '    </div>'+
            '    <div style="width:205px;float:left;overflow:hidden;">'+
            '    	<div style="width:202px;height:15px;background:url('+resourceUrl+'/info_top.png) center top no-repeat;margin-left:5px;"></div>'+
            '    	<div style="width:202px;min-height:40px;background:url('+resourceUrl+'/info_repeat.png) center top repeat-y;margin-left:5px;">'+
            '        	<div style="width:190px;margin:0px auto">'+
            '            	<h4 style="margin:0px 0px;padding:0px 0px 10px 5px;">FanClubCard Deals</h4>'+
            '                <p style="font-size:14px;margin:0px 0px 0px 0px;padding:0px 3px;">'+r.Details+
            '                </p>'+
            '            </div>'+
            '        </div>'+
            '    	<div style="width:202px;height:13px;background:url('+resourceUrl+'/info_bottom.png) center top no-repeat;margin-left:5px;"></div>'+
            '    </div>'+
            '    <div style="clear:both;overflow:hidden;padding-top:10px;">'+
            '    	<a href="http://maps.google.com/maps?saddr=&daddr='+r.Address+'&hl=en" target="_blank" style="width:122px;height:28px; display:inline-block;float:left;background:url('+resourceUrl+'/info_btn.png) 0px 0px no-repeat;"></a>'+
            '        <a href="'+(r.BusinessPage==''?'#':'/Home/'+r.BusinessPage)+'" style="width:150px;height:28px; display:inline-block;float:left;background:url('+resourceUrl+'/info_btn.png) -124px 0px no-repeat;margin:0px 0px 0px 50px;"></a>'+
            '    </div>'+    
            '</div>';
            return s;
    }
        
    var bounds = map.getBounds();  
   
    var array=vendors;
    for(var s=0;s<array.length;s++){  
        GetPoint(array[s],s);  
    }  
      
   }  
}  

function initCharityTabbar(){
    $('.logos .tab>li>a').click(function(){
        getCharities($(this).attr('categoryId'), $(this).attr('userId'), $(this).attr('renewCard')); 
        $('.logos .tab .current').removeClass('current');
        $(this).addClass('current');
    });

    $('.logos .tab>li>a:first').click();//loading first
}

function getCharities(categoryId, userId, renewCard){
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Home/CharityLogos",
        data: "{categoryId:\""+categoryId+"\"}",
        dataType: "json",
        error:function(xhr,err){ 
            alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status); 
            alert("responseText: "+xhr.responseText);
        },
        success:function(data){
            $('.logoscroller-container .list').empty();
            $(data).each(function(){
                $('.logoscroller-container .list').append('<li><div class="charity'+this.Id+'"></div>'+
                '<div class="charityContent">'+
                '<input type="button" class="buyNow" value="BUY NOW"  onclick="SHOPPINGCART.AddLine('+this.Id+',1,'+ userId +',' + renewCard + ',SHOPPINGCART_AddLineSuccess)"/>'+
                '<input type="button" class="moreInfo" value="MORE INFO" onclick="ShowCharityInfo('+this.Id+', ' + userId +',' + renewCard + ',\''+encodeURIComponent(this.CharityName)+'\',\''+encodeURIComponent((!this.Description?'':this.Description))+'\',\''+encodeURIComponent(this.CharityLogo)+'\')" />'+
                '</div>'+
                '<img width="188" height="140" src="'+this.CharityLogo+'" alt="'+this.CharityName+'"></li>');
            });
            $('.logoscroller-container').jScrollPane({ showArrows: true });
            $(".charityContent").parent().hover(function() {
                $(this).find('.charityContent').stop().hide().css('opacity',1).fadeIn();
            },
            function() {
                $(this).find('.charityContent').stop().hide().css('opacity',1).fadeOut();
            });
        }
    });
}

function ShowCharityInfo(id,userId, renewCard, name,description,logo){
	if(description == '')
		description = "Thanks for supporting our charity! We'll be providing more information for our charity very soon!";
		
    $('#charity-msg>h1.name').text(decodeURIComponent(name));
    $('#charity-msg>div.content>div.top>img.logo').attr("src",decodeURIComponent(logo));
    $('#charity-msg>div.content>div.top>div.description').html(decodeURIComponent(description));
    $('#charity-msg>div.content>div.bottom>input.btn').unbind('click');
    $('#charity-msg>div.content>div.bottom>input.btn').click(function(){
        SHOPPINGCART.AddLine(id,1, userId, renewCard,ShowCharityInfo_AddLineSuccess);
    });
    $('#charity-msg').popup({ closeBtn: 'a.close' });
}

function ShowCharityInfo_AddLineSuccess(data,callbackData){
    if(data.success){
        $('.callbackMsg').jGrowl("add line successfully.", { life: 300 });
		if(callbackData.userId == null)
			location.href="/ShoppingCart/Index";
		else
			location.href="/Home/Cart?userId=" + callbackData.userId + "&productId=" + callbackData.renewCard;
    }else{
        alert('add line faild.');
        $('.callbackMsg').jGrowl((data.msg?data.msg:'add line faild.'), { life: 300 });        
    }
}

function SHOPPINGCART_AddLineSuccess(data,callbackData){
    if(data.success){
        $('.charity'+callbackData.charityId).jGrowl("add line successfully.", { life: 300 });
		location.href="/ShoppingCart/Index?userId=" + callbackData.userId;
    }else{
        alert('add line faild.');
        $('.charity'+callbackData.charityId).jGrowl((data.msg?data.msg:'add line faild.'), { life: 300 });        
    }
}

var SHOPPINGCART={
    AddLine:function(charityId,quantity,userId, renewCard, successCallback,errorCallback)
    {
        this.Query('/ShoppingCart/AddCardLine', '{charityId:' + charityId + ',quantity:' + quantity + ', userId:' + userId +', renewCard:' + renewCard +'}', function (xhr, err) {
            if (errorCallback) errorCallback(xhr.responseText);
        },successCallback,{charityId:charityId,quantity:quantity, userId:userId, renewCard:renewCard});
    },
    UpdateQuantity:function(lineId,quantity,successCallback,errorCallback)
    {
        this.Query('/ShoppingCart/UpdateQuantity','{lineId:'+lineId+',quantity:'+quantity+'}',function(xhr,err){
            if(errorCallback)errorCallback(xhr.responseText);
        },successCallback,{lineId:lineId,quantity:quantity});
    },
    RemoveLine:function(lineId,successCallback,errorCallback)
    {
        this.Query('/ShoppingCart/RemoveLine','{lineId:'+lineId+'}',function(xhr,err){
            if(errorCallback)errorCallback(xhr.responseText);
        },successCallback,{lineId:lineId});
    },
    Clear:function(successCallback,errorCallback)
    {
        this.Query('/ShoppingCart/Clear','{}',function(xhr,err){
            if(errorCallback)errorCallback(xhr.responseText);
        },successCallback);
    },
    Query:function(url,data,errorCallback,successCallback,callbackData){
        $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: url,
        data: data,
        dataType: "json",
        error:function(xhr,err){
            if(errorCallback)errorCallback(xhr,err,callbackData);
        },
        success:function(result){
            if(successCallback)successCallback(result,callbackData);
        }
    });
    },
    InitUI:function(){
        $('#updateCart').click(function(){
            $("#shoppingCart").submit();
        });

        $('#continueshopping').click(function(){
            location.href='/Home/Charity';
        });

        $('#emptyCart').click(function(){
            SHOPPINGCART.Clear(function(data){
                if(!data.success){
                    alert(data.msg);
                }else{
                    location.reload();
                }
            });
        });
    }
};

function showDealPopup(deal) {
    /*$.fn.jmodal({
        initWidth:400,
        title: deal.VendorName,
        content: deal.HTML
    });*/
    $('#onlineDealsPopup').popup({
        closeBtn: 'a.close',
        onClose: function () {
            $('#onlineDealsPopup>.popupContent').empty();
        },
        onShow: function () {
            $('#onlineDealsPopup>.popupContent').append('<h3 style="margin:15px 15px 0px 15px;">' + deal.VendorName + '</h3>')
                                           .append('<div style="padding:5px 15px 15px 15px;">' + deal.HTML + '</div>');
        }
    });
    return false;
}
