/**
 * General utilities for the Nokia "OviServ" pages
 * @author Adam J. McIntyre -- adam.mcintyre@isobar.com
 */

;ISOBAR = (typeof ISOBAR !== "undefined") ? ISOBAR : {};
;ISOBAR.oviserv = (typeof ISOBAR.oviserv !== "undefined") ? ISOBAR.oviserv : {};
;ISOBAR.browser = {};
;ISOBAR.env = {};

;(ISOBAR.oviserv.utils = function($){
    var $features;
    
    return{
        init : function(){
            var o = this;

            $(window).bind('load',function(){
                if(typeof ISOBAR.browser.ie6 !== "undefined" && ISOBAR.browser.ie6){
                    o._fixIE6borders();  
                    $('li.feature .shadow').each(function(){
                        var bg = $(this).css('backgroundImage').replace(/url\(["']?/i,'').replace(/["']?\)$/,'');
                        this.style.filter = 
                            "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + bg + "', sizingMethod='scale')";
                        this.style.background = "none";
                    });                     
                }
            });

            $(document).ready(function(){
                // Globals: Is this a flavor of IE?
                var isIE = ISOBAR.browser.isIE = $.browser.msie;
                var version = parseFloat($.browser.version);
                ISOBAR.browser.ie6 = (isIE & version < 7) && $('body').addClass('ie6').length > 0;
                ISOBAR.browser.ie7 = (isIE & version < 8 & version > 6) && $('body').addClass('ie7').length > 0;
                ISOBAR.browser.ie8 = (isIE & version < 9 & version > 7) && $('body').addClass('ie8').length > 0; 
              
                // Set up page environment variables
                ISOBAR.env.isRTL = $('body').attr('dir') == 'rtl';              
                                
                var $pp = $('#product-page');

                // Determine which type of page we're on and delegate appropriately
                if($pp.hasClass('ovi-landing')){
                    o._init_oviLanding();
                } 
                
                $pp.find('.external').bind('click',function(e){
                    e.preventDefault();
                    window.open($(this).attr('href'));        
                });  
                
                if(ISOBAR.browser.isIE){
                    o._attachPIE();    
                }  
            });   
        },
        // Attach CSS PIE behaviors for dropshadows, border radius, etc.
        _attachPIE : function(){
            if(typeof PIE === "undefined"){
                return false;
            }
            
            var pieSelectors = [
                '#product-navigation li','#product-page .blue-button .edge','#gallery-navigation .gallery-tabs',
                '#gallery-navigation .gallery-tabs a.first-item', '#gallery-navigation .gallery-tabs a.last-item',
                '#gallery-navigation .carousel li', '#hero div.options-content .bd', '#hero .options-content .product-information',
                'div#social-bar', 'div#share-bar', '#social-bar div.extra-options', 'div#page-content', '#product-page .features .hero-feature .callout-content',
                'div#software-update.module', '#software-update .hd', '#software-update.module div.bd', '#accessories-module.module div.curve',
                '#product-page .module .bd', '#product-page .module .ft' 
            ];    
            
            $(pieSelectors.join(',')).each(function(){
                PIE.attach(this);
            });
        },
        _fixIE6borders : function(){
            var $pp = $('#product-page');
            
            $('#content-container css3-container:eq(0)').addClass('ie6-fix');
            if($pp.hasClass('ovi-landing') && $('#social-bar').length > 0){
                $('#social-bar').prev().css({
                    'left' : 15,
                    'top' : $('#social-bar').position().top
                });
            }

            if($('body').attr('dir') == "rtl"){
                $('#page-content').addClass('ie6-fix');
            }
        },
        _init_oviLanding : function(){
            var o = this;
            
            if(typeof sIFR_3 === "undefined"){
                return false;
            }
            
            sIFR_3.replace(nokialarge_regular, {
              selector: 'h1.sifr-replace',
              css: ['.sIFR_3-root { font-size:24px; leading:-2; color:#FFFFFF; background-color:transparent; }',
                 'a { color:#44aa33; text-decoration:none; }',
                 'a:hover { color:#337f26; text-decoration:none; }'],
              paddingTop: '0',
              wmode: 'transparent'
            });

            $('h3.sifr-replace').each(function(){
                $(this).attr('data-height',$(this).get(0).offsetHeight)
            });
                       
            sIFR_3.replace(nokialarge_regular, {
              selector: 'h3.sifr-replace',
              css: ['.sIFR_3-root { font-size:18px; leading:-8; color:#44aa33; background-color:transparent; }',
                 'a { color:#44aa33; text-decoration:none; }',
                 'a:hover { color:#337f26; text-decoration:none; }'],
              paddingTop: '0',
              wmode: 'transparent'
            });

            $('h2.sifr-replace').each(function(){
                $(this).attr('data-height',$(this).get(0).offsetHeight)
            });

            sIFR_3.replace(nokialarge_regular, {
              selector: 'h2.sifr-replace',
              css: ['.sIFR_3-root { font-size:40px; line-height:22px; color:#333333; background-color:transparent; }',
                 'a { color:#44aa33; text-decoration:none; }',
                 'a:hover { color:#337f26; text-decoration:none; }'],
              paddingTop: '0',
              wmode: 'transparent'
            }); 
            
            // Level features boxes
            $(window).bind('load',function(){
                o.levelContent();
            });
            
            // Swap Ovi download link
            if($('.toggle-download-link').length > 1){
                if(navigator.platform.match(/mac/ig)){
                    $('.mac-link').removeClass('hidden');
                    $('.pc-link').addClass('hidden');    
                }                   
            } 
        },
        levelContent : function(){
            var o = this;
            var $features = $('#page-content .feature');
            
            // Is sIFR active and loaded?
            if(typeof sIFR_3 === "undefined" || (typeof sIFR_3 === "object" && ! $('body').hasClass('sIFR_3-active'))){
                $('#page-content .feature').each(function(){
                    $this = $(this);
    
                    $this.height($this.height()).addClass('fixed-height')
                        .find('img')
                        .addClass($this.hasClass('even') ? 'fixed-left' : 'fixed-right');
                }); 
            }
            else{
                // Only operate on elements that have been physically replaced via Flash
                if($('#product-page').find('.sifr-replace').length == sIFR_3.replacements.length){
                    $('#page-content .feature').each(function(){
                        var $this = $(this);
                        var $h3 = $this.find('h3');
                        var $h2 = $this.find('h2');
                        
                        var h3Height = parseInt($h3.attr('data-height'));
                        var h2Height = parseInt($h2.attr('data-height')) + parseInt($h2.css('margin-bottom'));
                        
                        $h3.css({
                            top : -1 * (h3Height + h2Height),
                            marginBottom : 0
                        });
                        
                        var $text = $this.find('p:first');
                        var mt = parseInt($text.css('margin-top'));
                        $text.css({
                            marginTop : -1 * ((h3Height + h2Height) - mt) + mt
                        });

                        $this.addClass('fixed-height')
                            .find('img')
                            .addClass($this.hasClass('even') ? 'fixed-left' : 'fixed-right');
                        
                        var fHeight = $this.get(0).offsetHeight;
                        $this.height(fHeight);

                        var cHeight = $this.find('.copy-container').get(0).offsetHeight;
                        $this.height(fHeight > cHeight ? fHeight : cHeight);                               

                        if(ISOBAR.browser.ie6){
                            $this.parent().addClass($this.hasClass('even') ? 'fixed-left' : 'fixed-right');
                        }                            
                    });                    
                }
                else{
                    setTimeout(function(){
                        o.levelContent();
                    },150);    
                }                     
            }
        }
    }
}(jQuery)).init(); 

/***
 * Utility class for building the XML feed-based Ovi Store carousel.
 */
;(ISOBAR.oviserv.OviFeed = function(){
  var FEED_URL = "http://feeds.store.ovi.com/service/bannerrequest.ashx?line=top50apps";         
    var $appList = null;
    var LI_TEMPLATE = '<li>' +
        '<a href="{url}" target="_blank"><img src="{img}" alt="{name}"></a>' +
        '<a href="{url}" target="_blank">{formattedName}</a>' +
        '<span class="label">{category}</span>' +
        '<p class="price">{price}</p></li>';
    var largeIcons = false;
    var totalBanners = 6;
    var tmpAppId, tmpAppUrl = null;   //TK placeholder for app ID

    return{
        init : function(){
            var o = this;
            
            if(typeof window.oviFeedUrl !== "undefined" && window.oviFeedUrl.length > 0){
                FEED_URL = window.oviFeedUrl;
            }

            $appList = $('.apps-list');
            largeIcons = $appList.parent().hasClass('large-icons'); 
            
            if(largeIcons){
                totalBanners = 2;
            }

            if($appList.length > 0){
                $(window).bind('load',function(){                
                    o._showLoading()._fetchFeed();
                });    
            }
            $(document).ready(function(){
                // Remove placeholder image
                $('.apps-list-placeholder').remove();    
            });                                    
        },
        /***
         * Fetches the feed from vendor URL.
         */
        _fetchFeed : function(){
            var o = this;
            var fl = new flensed.flXHR({ 
                autoUpdatePlayer:true, 
                instanceId:"iso_ovi-store", 
                noCacheHeader : false,
                onreadystatechange:function(xhr){
                    if(xhr.readyState == 4){
                        o._handleReadyState(xhr);
                    }
                }
            });
            fl.open("GET",FEED_URL); 
            fl.send(null);                                                                        
        },
        /***
         * Kicks things off once XHR completes.
         * @param {Object} xhr XHR Object returned by completed request.
         */
        _handleReadyState : function(xhr){
            this._buildHtml($(xhr.responseXML))._hideLoading();
        },
        /***
         * Renders the Store carousel's HTML.
         * @param {jQueryObject} xml jQuery Object representing XML we'll be parsing.
         */
        _buildHtml : function(xml){
            var banners = xml.find('banner:lt(' + totalBanners + ')');
            var h = "";

            banners.each(function(){
                var $b = $(this);      
                var name = jQuery.trim($b.children('name').text());
                var formattedName = name;                
                var nameWords = name.split(/\s/);
                var img;
                
                if(largeIcons){
                    var $imgs = $b.find('asset');
                    var max = 0;

                    $imgs.each(function(){
                        var $i = $(this);
                        var w = parseInt(jQuery.trim($i.find('width').text()),10);

                        if(w > max){
                            max = w;
                            img = jQuery.trim($i.find('url').text());
                        }
                    });
                }
                else{
                    img = jQuery.trim($b.find('width:contains("96")').parent().find('url').text());
                }                

                for(var i = 0; i < nameWords.length; i++){
                    if(nameWords[i].length > 30){    // If this particular word is greater than 30 characters, truncate name
                        formattedName = nameWords.slice(0,i).join(' ');    // Save the valid, fitting words.
                        formattedName += nameWords[i].substr(0, 5) + '&hellip;';    // Truncate word, adding '...'
                        break;
                    }    
                }
                tmpAppUrl = jQuery.trim($b.children('url').text());     //TK get app URL
                tmpAppId = tmpAppUrl.match(/^.*\/([0-9]*)(.*)$/)[1];    //TK get app id
                // tmpAppUrl += "?cid=ovistore-fw-ilc-own-acq-xml-nokiacomovibynokia-" + window.oviFeedTagSite + "-14-" + tmpAppId;   //TK make URL with tracking code

                h += LI_TEMPLATE.replace(/{url}/g,tmpAppUrl)
                    .replace(/{name}/g,name)
                    .replace(/{formattedName}/g,formattedName)
                    .replace('{img}',img)     
                    .replace('{category}',jQuery.trim($b.find('category > category > category:first').attr('displayname')))
                    .replace('{price}',jQuery.trim($b.children('price').text()))
            });
           
            $appList.html(h);
            
            if(! largeIcons){
                $appList.find('.price').remove();
            }       
            
            return this;
        },
        /***
         * Shows a loading bar while the carousel builds.
         */
        _showLoading : function(){
            $appList.fadeOut();
            return this;    
        },
        /***
         * Hides the loading bar once things are built.
         */
        _hideLoading : function(){
            $appList.fadeIn();
            return this;
        }
    }
}()).init();        
