// Custom fonts
// sIFR configuration
var din = {
	src: '/js/sifr3-r436/din.swf'
};

sIFR.activate(din);

sIFR.replace(din, {
    selector            : 'h1,h2',
    css                 : {
                            '.sIFR-root': {
                                    'font-family'       : 'DINPro-light'
                            },
                            'strong': {
                                    'font-family'       : 'DINPro-bold',
                                    'font-weight'       : 'plain'
                            },
                            'a':{
                                    'color'             : '#000000'
                            }
                          },
    repaintOnResize     : false,
    selectable          : false,
    wmode               : 'transparent'
});
sIFR.replace(din, {
    selector            : 'p.splashSubtitle',
    css                 : {
                            '.sIFR-root': {
                                    'font-family'       : 'DINPro-light',
                                    'color'             : '#ffffff',
                                    'text-transform'    : 'uppercase'
                            },
                            'strong': {
                                    'font-family'       : 'DINPro-bold',
                                    'font-weight'       : 'plain'
                            },
                            'a':{
                                    'color'             : '#000000'
                            }
                          },
    repaintOnResize     : false,
    selectable          : false,
    wmode               : 'transparent'
});
sIFR.replace(din, {
  selector              : 'a.tab',
  css                   : {
                            '.sIFR-root': {
                                    'font-family'       : 'DINPro-light'
                            },
                            'a':{
                                    'color'             : '#000000'
                            }
                          },
  repaintOnResize       : false,
  forceSingleLine       : true,
  selectable            : false,
  wmode                 : 'transparent',
  onRelease             : function(fi){
                            $(fi.getAncestor()).click();
                          },
  filters               : {
                            DropShadowFilter:{
                                blurY           : 0,
                                blurX           : 0,
                                strength        : 0.7,
                                alpha           : 1,
                                color           : '#ffffff',
                                angle           : -90,
                                distance        : 1
                            }
                          }
});

function miniShopDetail()
{
    this.shop       = {
                        id          : null,
                        title       : '', 
                        style       : null, 
                        superShop   : null
                      };
    this.shopsXml   = '/reseller/MinishopPicker.action?shopsAsXml';
    this.onlyShop   = '';
    this.searchFor  = '';
    this.pageLimit  = 6*6;
    this.startOffset= 0;

    this.init = function()
    {
        $('.tab:last').hide();
        var url = window.location.toString();
        if(url.indexOf('shop=') != -1)
        {
            var parameters = url.split('?')[1].split('&');
            for(i in parameters)
            {
                if(parameters[i].split('=')[0] == 'shop')
                {
                    this.onlyShop = parseInt(parameters[i].split('=')[1]);
                    myConsole('Searching for shop '+this.onlyShop);
                    
                    $('.on').removeClass('on');
                    $('.tab:last').show().addClass('on');
                }
            }
        }
        
        this.readXml(this.listMinishops);
    }

    this.setShop = function(data)
    {
        this.shop       = {
                            id          : data.shop,
                            title       : data.title,
                            style       : data.style,
                            superShop   : data.parentShop,
                            version     : data.version,
                            embedCode   : data.embedCode
                          };
    }

    this.open = function()
    {
        var thisObj         = this;
        var blackOverlay    = $('<div class="blackOverlay"></div>')
                                .css('height', $(document).height())
                                .css('opacity', 0)
                                .click(function(){
                                    thisObj.close();
                                    return false;
                                });
        var versionTwo      = '';
        var popupBody       = $('<div class="popupBody"><div class="popupTop"><div class="popupBottom"><div class="content"></div><div class="clean"></div></div></div></div>');

        if(this.shop.version == 2)
        {
            versionTwo = '&amp;version=2';
        }

        $(window).resize(function(){
            if($(this).height()>$(document).height())
            {
                $('.blackOverlay').css('height', $(this).height())
            }
            $('.popupBody').css('left', ($(this).width()-$('.popupBody').width())/2);
        });
        $('body')
            .prepend(blackOverlay.animate({opacity:0.5}))
            .prepend(popupBody);

        popupBody
            .find('.content')
                .append($('<h3></h3>').text(this.shop.title))
                .append($('<a class="close" href="#">&nbsp;</a>')
                    .click(function(){
                        thisObj.close();
                        return false;
                    })
                )
                .append($('<div  class="minishop"><div id="RAflashWidget"></div></div>'))
                .append($('<a href="/reseller/MinishopPicker.action?shop='+this.shop.id+'&minishopSelected=Start+nu'+versionTwo+'">'
                            +'<img border="0" src="/images/splash/shareAndEarn.jpg" width="300" height="67" alt="Sell and Earn"/>'
                         +'</a>'
                         +'<p>or just click following to share:</p>')
                 )
                 .append($('<div class="socialSites"></div>')
                            .append($('<div id="embedCode" class="hidden"><textarea>'+generateEmbedCode({shopid : this.shop.id})+'</textarea></div>'))
                            .append($('<a href="#" id="FBpost"><img src="/images/MiniShop-wizard/SocialSitesIcons/facebook-32x32.png" width="32" height="32" alt="Share on Facebook"/></a>')
                              /*          .click(function(){
                                            myConsole('Sharing at Facebook:\n'
                                                        +' thisObj.shop.id: '+thisObj.shop.id
                                                        +' thisObj.shop.style: '+thisObj.shop.style
                                                        +' thisObj.shop.superShop: '+thisObj.shop.superShop
                                                        +' thisObj.shop.title: '+thisObj.shop.title);

                                            FB.ensureInit(function () {
                                                FB.Connect.requireSession(function(){
                                                    var fbLoggedUser = FB.Connect.get_loggedInUser();

                                                    if(fbLoggedUser != null && fbLoggedUser != '')
                                                    {
                                                        if(thisObj.shop.version == 2)
                                                        {
                                                            facebookSendToWall('http://www.redantenna.com', thisObj.shop.title, {
                                                                imgsrc      : 'http://minishop.redantenna.com/share/acmo.php?s='+thisObj.shop.id+'&format=.jpg',
                                                                swfsrc      : 'http://minishop.redantenna.com/msv2/dsPlayer_As3_callback.swf',
                                                                flashvars   : 'shopid='+thisObj.shop.id+'&version=2'
                                                            }, thisObj.shop.id, null, null, fbLoggedUser, thisObj.shop.style);
                                                        } else {
                                                            facebookSendToWall('http://www.redantenna.com', thisObj.shop.title, {
                                                                imgsrc      : 'http://blue.redantenna.com/widget/styleeditor/XMLstyleEditor.action?image&widgetStyle='+thisObj.shop.style+'&format=.jpg',
                                                                swfsrc      : 'http://red.redantenna.com/redshoplet/coverflowSmallFacebook.swf',
                                                                coverConfig : 'http://red.redantenna.com/coverconfig?id='+thisObj.shop.id,
                                                                coverFeed   : 'http://red.redantenna.com/feed?id='+thisObj.shop.id
                                                            }, thisObj.shop.id, null, null, fbLoggedUser, thisObj.shop.style);
                                                        }
                                                    }
                                                });
                                            });

                                            return false;
                                        })*/
                                    )
                            //.append($('<a href="#"><img src="/images/splash/myspace.gif" width="32" height="32" alt="Share on MySpace"/></a>'))
                            .append($('<a href="#" id="BloggerInstall"><img src="/images/MiniShop-wizard/SocialSitesIcons/blogger-32x32.png" width="32" height="32" alt="Share on Blogger"/></a>')
                                        /*.click(function(){
                                            myConsole('Sharing at blogger');
                                            if(typeof(thisObj.shop.embedCode) == 'undefined')
                                            {
                                                $.ajax({
                                                    url         : '/widget/styleeditor/EmbedXML.action',
                                                    type        : 'get',
                                                    data        : {shop:thisObj.shop.id},
                                                    success     : function(xml){
                                                                    openBlogger('http://www.redantenna.com', thisObj.shop.title, $(xml).find('widgetEmbedText TextHtml').text());
                                                                  }
                                                });

                                            } else {
                                                openBlogger('http://www.redantenna.com', thisObj.shop.title, thisObj.shop.embedCode);
                                            }
                                            return false;
                                        })*/)
                            .append($('<a href="#" id="WPinstall"><img src="/images/MiniShop-wizard/SocialSitesIcons/wordpress-32x32.png" width="32" height="32" alt="Share on Wordpress"/></a>')
                                        /*.click(function(){
                                            myConsole('Sharing at Wordpress');
                                            if(typeof(thisObj.shop.embedCode) == 'undefined')
                                            {
                                                $.ajax({
                                                    url         : '/widget/styleeditor/EmbedXML.action',
                                                    type        : 'get',
                                                    data        : {shop:thisObj.shop.id},
                                                    success     : function(xml){
                                                                    openWordpress('http://www.redantenna.com', thisObj.shop.title, $(xml).find('widgetEmbedText TextHtml').text());
                                                                  }
                                                });

                                            } else {
                                                openWordpress('http://www.redantenna.com', thisObj.shop.title, thisObj.shop.embedCode);
                                            }
                                            return false;
                                        })*/)
                 )
            .end()
            .css('left', ($(window).width()-popupBody.width())/2);

        bindShareButtons({
            title			: this.shop.title,
            description                 : 'powered by RedAntenna',
            shopId			: this.shop.id
        });

        sIFR.replace(din, {
          selector: 'h3',
          css: {
                '.sIFR-root': {
                        'font-family' 		: 'DINPro-light'
                }
          },
          selectable :false,
          wmode:'transparent'
        });
        this.embed();
    }

    this.close = function()
    {
        $('.blackOverlay').fadeOut('slow', function(){$(this).remove();});
        $('.popupBody').fadeOut('slow', function(){$(this).remove();});
    }

    this.embed = function()
    {
        swfobject.removeSWF('widget');
        var ms 			= $('.minishop');
        var swfObjectWidth 	= 300;
        var swfObjectHeight     = 280;
        var coverConfig         = '/widget/styleeditor/EmbedXML.action?shop='+this.shop.id;
        var coverFeed           = '/feed.action?shop='+this.shop.id;
        var swfUrl              = '/widgetRequest/'+this.shop.id+'/small.swf?random='+Math.random()+Math.random()+Math.random()+Math.random();
        var flashvars           = 'coverConfig='+encodeURIComponent(coverConfig)+'&coverFeed='+encodeURIComponent(coverFeed);

        if(this.shop.version == 2)
        {
            swfUrl              = 'http://minishop.redantenna.com/msv2/dsPlayer_As3_callback.swf';
            flashvars           = 'shopid='+this.shop.id+'&version=2'
        }

        myConsole('Loading minishop;\n Coverconfig: '+coverConfig+' \nCoverFeed: '+coverFeed);

        if(ms.find('#RAwidgetContainer').length == 0)
        {
            ms.append($('<div id="RAwidgetContainer"></div>'));
        }
        swfobject
                .embedSWF(
                    swfUrl,
                    'RAwidgetContainer',
                    swfObjectWidth,
                    swfObjectHeight,
                    '9.0.0',
                    'expressInstall.swf',
                    false,
                    {
                      menu      : false,
                      flashvars : flashvars,
                      wmode     : 'transparent'
                    },
                    {
                      id        : 'widget',
                      name      : 'widget'
                    }
              );
        ms.fadeIn('slow');
    }

    this.listMinishops = function(xml, thisObj)
    {
        if(typeof(thisObj) == 'undefined')
        {
            thisObj             = this;
        }

        var countOfMinishops    = $(xml).find(':first').attr('count');
        var numberOfPages       = Math.ceil(countOfMinishops/thisObj.pageLimit);
        var currentPage         = Math.ceil(thisObj.startOffset/thisObj.pageLimit)+1;
        var pagingContainer     = $('.paging');

        if(countOfMinishops > thisObj.pageLimit)
        {
            pagingContainer
                .find('.currentPage')
                    .text(currentPage)
                .end()
                .find('.pagesCount')
                    .text(numberOfPages)
                .end();

            // show the next button
            if(thisObj.startOffset < (numberOfPages*thisObj.pageLimit) && $('.browseButton.nextPage').length == 0)
            {
                $('<a href="#" class="browseButton nextPage">&nbsp;</a>')
                    .click(function(){
                        thisObj.startOffset += thisObj.pageLimit;
                        thisObj.readXml(thisObj.listMinishops);
                        return false;
                    })
                    .appendTo($('#pagingTop,#pagingBottom'));
            }
            if(numberOfPages == currentPage)
            {
                $('.browseButton.nextPage').remove();
            }

            // show the previous button
            if(thisObj.startOffset > 0 && $('.browseButton.prevPage').length == 0)
            {
                $('<a href="#" class="browseButton prevPage">&nbsp;</a>')
                    .click(function(){
                        thisObj.startOffset -= thisObj.pageLimit;
                        if(thisObj.startOffset < 0)
                        {
                            thisObj.startOffset = 0;
                        }
                        thisObj.readXml(thisObj.listMinishops);
                        return false;
                    })
                    .prependTo($('#pagingTop,#pagingBottom'));
            }
            if(currentPage <= 1)
            {
                $('.browseButton.prevPage').remove();
            }
        }

        $('#minishopsList').empty();
        $(xml)
            .find('shop')
                .each(function(i){
                    var thisItem = $(this);
                    //setTimeout(function(){
                        var id          = thisItem.attr('id');
                        var style       = thisItem.attr('style');
                        var superShop   = thisItem.attr('supershop');
                        var version     = 1;
                        var title       = thisItem.find('title:first').text();

                        if(typeof(thisItem.attr('version')) != 'undefined' && thisItem.attr('version').length > 0)
                        {
                            version = parseInt(thisItem.attr('version'));
                        }
                        if(version == 2)
                        {
                            var embedCode = generateEmbedCode({shopid : id});
                        }

                        var minishopItem = $('<a href="#" id="'+id+'" rel="'+style+';'+superShop+'" class="minishopThumb"><img src="http://minishop.redantenna.com/coverart.jpg?shopid='+id+'" width="132" height="132" alt="'+title+'"/><br/>'+title+'</a>')
                                            .click(function(){
                                                thisObj.setShop({
                                                    shop         : $(this).attr('id'),
                                                    title        : $.trim($(this).text()),
                                                    style        : parseInt($(this).attr('rel').split(';')[0]),
                                                    parentShop   : parseInt($(this).attr('rel').split(';')[1]),
                                                    version      : version,
                                                    embedCode    : embedCode
                                                });

                                                thisObj.open();
                                                return false;
                                            });

                        $('#minishopsList').append(minishopItem.fadeIn('slow'));
                    //}, i*200);
                });
        }

    this.readXml = function(callback)
    {
        try{
            var thisObj = this;
            $('#minishopsList').ajaxLoadingAnim();
            $.ajax({
                url     : this.shopsXml,
                type    : 'get',
                data    : {
                            searchFor   : this.searchFor,
                            limit       : this.pageLimit,
                            start       : this.startOffset,
                            shop        : this.onlyShop
                          },
                success : function(xml){callback(xml, thisObj);},
                error   : function(xhr, textStatus, errorThrown){
                            alert("ERROR: Could not fetch the MiniShops list:\n"
                                +xhr.statusText+'\n'
                                +xhr.status+'\n'
                                +xhr.responseText+'\n'
                                +xhr.getAllResponseHeaders()+'\n'
                                +textStatus+'\n'
                                +errorThrown
                                );
                          }
            });
        } catch(e) {
            myConsole(e);
        }
    }
}

// jQuery init functions
$(function(){
    var shopDetail = new miniShopDetail();
    shopDetail.init();
    
    $('.tab:first')
        .click(function(){
            $('.on').removeClass('on');
            $(this).addClass('on');
            $('.tab:last').hide();

            shopDetail.onlyShop   = '';
            shopDetail.searchFor  = '';
            
            shopDetail.readXml(shopDetail.listMinishops);
            return false;
        });
    $('.tab:last')
        .click(function(){
            $('.on').removeClass('on');
            $(this).addClass('on');
            return false;
        });

    var defaultSearchString = 'Enter an artist name, single or both...';

    $('input.search')
        .val(defaultSearchString)
        .focus(function(){
            if($.trim($(this).val()) == defaultSearchString)
            {
                $(this).val('');
            }
        })
        .parents('form')
            .submit(function(){
                try{
                    shopDetail.searchFor = $.trim($('input.search').val());
                    $('.on').removeClass('on');
                    $('.tab:last').show().addClass('on');
                    shopDetail.readXml(shopDetail.listMinishops);
                } catch(e) {
                    myConsole(e);
                }
                return false;
            });
    $('.popularSearches a').click(function(){
        $('input.search').val($(this).text());
        return false;
    });
});
