/* pwConnect.js plugin information

    This Javascript plugin lets you embed ProductWiki reports directly on your site.
    Reports can show up directly on the page as an iFrame or as a button that causes a pop-up.

    This plugin requires the use of jQuery.

    Copy and paste the following script include in your code    
    <script type="text/javascript" src="http://www.productwiki.com/js/v3/plugins/pwConnect.js"></script>    

    Copy and past the below HTML in the area you want the iframe or button to show up           
    <a href="http://www.productwiki.com/skutype/sku/" class="ProductWikiConnect">product title</a>
                    

    in both the HTML snippet you must replace some of the values above with real information.
        - sku type:  the type of SKU information you store
            * possible values: UPC, EAN, ASIN, MPN
        - sku id: the actual id of the product
        - product title: the actual title of the product
        
        
    
    Filled in basic example
    in this case: partnerid=123456, sku type=upc, sku id=086483071492, product title=Sanyo Xacti VPC-CG9
    <html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
        <script type="text/javascript" src="http://www.productwiki.com/js/v3/plugins/pwConnect.js"></script>
    </head>
    <body>
        <a href="http://www.productwiki.com/upc/086483071492/" class="ProductWikiConnect" >Sanyo Xacti VPC-CG9</a>      
    </body>
    </html>
    
    
    Manual example, rendered as iFrame, inside of a tab, only load iFrame when the tab click happens.   
    <a id='ProductWikiAnchor' href="http://www.productwiki.com/upc/086483071492/" class="ProductWikiConnect ProductWikiEmbed ProductWikiManual">Sanyo Xacti VPC-CG9</a>
    
    <script type="text/javascript">
        $('#tab').click(function(){
            RunPWConnect('#ProductWikiAnchor', {            
                disabledmodules: 'twitter', 'popular'
            });
        });
    </script>
                                
    Manual Options
        anchor - the id of the ProductWiki anchor
        urloverride - if you want to use a canonical URL, and not the url that's in the address bar
        disabledmodules - comma separated list of modules you DON'T want to show up
            values: description, competitors, related, popular, twitter 
*/
window.pwConnect = {};
(function($){
    $.fn.extend({
        pwConnect: function(settings){
            var defaults = {
                apiurl: 'http://pwc.productwiki.com',
                rendermode: 'popup', /* embedded,popup*/
                skutype: 'upc',
                sku: '',
                producttitle: '',
                productprice: '',
                resizehtml: '/productwiki.html',
                domainoverride: '',
                urloverride: '',
                disabledmodules: '',
                showempty: false,
                anchor: ''
            };
            
            var settings = $.extend(defaults, settings);
            var iframeSet = false;
            var shouldShow = true;
            var isMatch;                                        
            var product='';         
            var localURL = (settings.urloverride ? settings.urloverride : location.href);
                                    
            if(localURL.indexOf('#') > -1){
                localURL = localURL.substring(0, localURL.indexOf('#'));
            }
            
            //percent encode the URL
            localURL = localURL.replace(/%/g,'%25').replace(/\?/g,'%3F').replace(/&/g,'%26').replace(/\!/g,'%21').replace(/\*/g,'%2A')
                .replace(/\(/g,'%28').replace(/\)/g,'%29').replace(/;/g,'%3B').replace(/:/g,'%3A').replace(/@/g,'%40').replace(/=/g,'%3D')
                .replace(/\+/g,'%2B').replace(/\$/g,'%24').replace(/,/g,'%2C')
                .replace(/#/g,'%23').replace(/\[/g,'%5B').replace(/\]/g,'%5D');
                    
            
                                    
            return this.each(function(){
                
                //setup rendering container
                var $container = $(this);
                if(settings.$container){
                    $container = settings.$container;
                }
                else{
                    if(settings.anchor.length > 0){
                        $container = $('#'+settings.anchor).parent();
                    }
                }
                
                //if we don't have a container then return and don't do anything
                if(!$container){return;}
                
                if(iframeSet == false){     
                    // make AJAX call
                    var jsonURL = settings.apiurl + '/connect/match_connect.aspx?'
                            + 'title=' + settings.producttitle
                            + '&price=' + settings.productprice
                            + '&idtype=' + settings.skutype 
                            + '&idvalue=' + settings.sku.replace('.','-').replace('#','-') 
                            + '&url=' + localURL
                            + '&callback=?';
                            
                    $.getJSON(jsonURL, function(data){                                                      
                                $container.html('');
                                product = data.Product;
                                isMatch = data.IsMatch;
                                if(data.IsMatch==false){                                    
                                    shouldShow = settings.showempty;
                                }                                                                                                                           
                                            
                                if(settings.rendermode=='embed'){
                                    $pwiframeRenderContainer=$container;
                                    if(shouldShow==true) {renderiFrame();}                              
                                }
                                else if(settings.rendermode=='popup'){
                                    
                                    if(shouldShow==true){
                                        //create button
                                        $container.replaceWith(
                                            $(document.createElement('a'))
                                                            .attr('href', '#')
                                                            .attr('alt', settings.producttitle)
                                                            .attr('title', settings.producttitle)
                                                            .click(function(e){
                                                                e.preventDefault();
                                                                popup();
                                                                return false;
                                                            })
                                                        .append($(document.createElement('img'))
                                                            .attr('src','http://www.productwiki.com/images/buttons/pwproscons.png'))
                                            );
                                    }
                                }
                                
                                //ga tracking
                                /* google analytics 
                                $.getScript(('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js', function() {                                                           
                                    var ProductWikiPageTracker = _gat._getTracker("UA-273384-9");                           
                                    ProductWikiPageTracker._setReferrerOverride(localURL);
                                    ProductWikiPageTracker._trackPageview(data.PageURL);                            
                                }); */
                                
                                iframeSet=true;
                            });
                }
            
                
                function popup(){
                    window.open(constructURL(), "_blank", "height=800,width=800,top=20,left=20,status=yes,toolbar=no,menubar=no,scrollbar=yes,resizable=1");
                }
                
                function renderiFrame(){
                    if(!iframeSet){
                        $pwiframeRenderContainer.replaceWith(
                            $(document.createElement('iframe'))
                                .attr('src', constructURL())
                                .attr('height', '800px')
                                .attr('width', '100%')
                                .attr('scrolling', 'no')
                                .css('border-width','0px')
                                .attr('marginwidth', '0')
                                .attr('marginheight', '0')
                                .attr('frameborder', '0')
                                .addClass('ProductWikiIFrame')                      
                        );
                    }
                }
                
                function constructURL(){                        
                    var firstPart;                  
                    if(isMatch){
                        firstPart = settings.apiurl + product;
                    }
                    else if(settings.skutype=='asin' && settings.sku=='abc'){
                        if(product == ''){
                            firstPart = settings.apiurl + '/home/connectsku/' + settings.skutype + '/' + settings.sku;  
                        }
                        else{
                            firstPart = settings.apiurl + product;                          
                        }
                    }
                    else{
                        firstPart = settings.apiurl + '/home/connectsku/asin/abc/';
                    }
                    var aURL = firstPart
                        + '?' + 'product=' + settings.producttitle 
                        + '&clienturl=' + localURL
                        + '&clientdomain=' + (settings.domainoverride=='' ? '' : settings.domainoverride)
                        + '&html=' + (settings.resizehtml.indexOf('http') < 0 ? window.location.protocol + '//' + window.location.host + settings.resizehtml : settings.resizehtml)
                        + '&popup=' + (settings.rendermode=='popup' ? 'true' : 'false')
                        + '&disabledmodules=' + settings.disabledmodules
                        ;
                        
                    return aURL;
                }
                
                function isLoaded(){
                    return iframeSet;
                }
            });
        }
    });
    
    $(document).ready(function(){
        $('.ProductWikiConnect').each(function(e){
            if(!$(this).hasClass('ProductWikiManual')){
                RunProductWikiConnect($(this));
            }
        });
    });
        
    
})(jQuery);

function RunPWConnect(selector, args){  
    jQuery(selector).each(function(e){
        RunProductWikiConnect($(this), args);   
    });     
}

function RunProductWikiConnect($anchor, args)
{       
    //parse URL
    if($anchor.length > 0){
        var parts = $anchor.attr('href').split('/');
        
        var isGeneral = parts.length < 5;
        var isPartner = (parts[3] == 'partner');
        var isSku = (isGeneral ? false : ('upc,asin,ean,mpn,pgid'.indexOf(parts[3]) > -1 ? true : false));
        
        var theArgs = {
            skutype:  (isPartner ? 'partner' : (isGeneral ? 'asin' : (isSku ? parts[3] : 'label'))),
            sku: (isGeneral ? 'abc' : (isSku ? parts[4] : parts[3])),
            producttitle: $anchor.text(),
            rendermode: ($anchor.hasClass('ProductWikiEmbed') ? 'embed' : 'popup'),
            showempty: ($anchor.hasClass('ProductWikiOnlyMatched') ? false : true)
        };
        
        return jQuery($anchor).pwConnect(jQuery.extend(theArgs,args));
    }
}

function productwiki_resize( height , aURL ) {
    jQuery('iframe.ProductWikiIFrame').each(function(){
        if(aURL){
            //are they the same url. Some replacing and such is needed to clear out weird issues
            if(escape($(this).attr('src')).replace(/%2520/g,'%20') == aURL.replace(/%2520/g,'%20'))
                $(this).attr('height', height);
        }
        else{
            $(this).attr( 'height', height );
        }
    });
}
