var $j = jQuery.noConflict();

//window.onerror = errorHandler;

function errorHandler(msg, url, lno) {
    var parts = window.location.host.split('.');
    var sub = parts[0];
    
    if (url.search(/linkedin/i)!=-1) {
        var img = $j('img[rel="linkedin-connect"]');
        img.unbind('click');    
        img.attr('rel', 'linkedin-connect-offline');
        img.attr('src', '/skin/frontend/blank/theme048/images/social/linkedin_bw.png');
        img.attr('title', 'Linkedin is Offline. Please try later.');
        img.css('cursor', 'auto'); 
    } else if (url.search(/facebook/i)!=-1) {
        var img = $j('img[rel="facebook-connect"]');
        img.unbind('click');
        img.attr('rel', 'facebook-connect-offline');    
        img.attr('src', '/skin/frontend/blank/theme048/images/social/facebook_bw.png');
        img.attr('title', 'Facebook is Offline. Please try later.');
        img.css('cursor', 'auto'); 
    } else if (url.search(/twitter/i)!=-1) {
        var img = $j('img[rel="twitter-connect"]');
        img.unbind('click');
        img.attr('rel', 'twitter-connect-offline');        
        img.attr('src', '/skin/frontend/blank/theme048/images/social/twitter_bw.png');
        img.attr('title', 'Twitter is Offline. Please try later.');
        img.css('cursor', 'auto'); 
    }
    
    // Log Errors
    if (sub!='www') {
        var errorMsg = msg+'\n'+'Line: '+lno+'\n'+url;
        alert(errorMsg);
    } else {
        debugData = new Object;
        debugData['errorMessage'] = msg;
        debugData['errorNo'] = lno;
        debugData['errorUrl'] = url;
        $j.ajax({
            type: "POST",
            url: "/core/ajax/mailError/",
            data: debugData
         });
    }
     
    return (true);
}

function bindRemoveMessage(node) {
    node.click(function() {
        if($j("#messages_product_view").length > 0) {
            $j('#messages_product_view').fadeOut("slow");
        } else if($j("#messages").length > 0) {
            $j('#messages').fadeOut("slow");
        } 
        return false; 
     });    
}

$j(document).ready(function() {
    bindRemoveMessage($j('#a-remove-msg'));
    
    if ($j("a[data='lightbox']").length>0) {
        $j("a[data='lightbox']").fancybox({
            'hideOnContentClick': true,
            'centerOnScroll': true,
            'titleShow': false,
            'transitionIn'    : 'elastic',
            'transitionOut'    : 'elastic',
            'easingIn'      : 'easeOutBack',
            'easingOut'     : 'easeInBack'
        });    
    } 

    $j("div[id^='div-triso-more']").click(function() {
        id = $j(this).attr('id').split('-');
            
        $j("#div-triso-more-"+id[3]).hide();
        $j("#div-triso-less-"+id[3]).show();
        $j("#div-triso-content-"+id[3]).fadeIn('slow');    
        
        return false; 
    });
    
    $j("div[id^='div-triso-less']").click(function() {
        id = $j(this).attr('id').split('-');
        
        $j("#div-triso-more-"+id[3]).show();    
        $j("#div-triso-content-"+id[3]).hide();
        $j("#div-triso-less-"+id[3]).hide();
            
        return false; 
    });
      
    $j(".triso-window-framebar").click(function() {
        var data = $j(this).attr('data');
        
        if (data) {
            id = data.split(':');
            window.open('http://' + location.host + '/framebar/bar/index/id/'+id[1]+'/url/'+$j.base64Encode($j(this).attr('href'))); 
        } else {
            window.open('http://' + location.host + '/framebar/bar/index/url/'+$j.base64Encode($j(this).attr('href'))); 
        }
        
        return false;
     });
     
     $j(".triso-window-framebar-clean").click(function() {
        var data = $j(this).attr('data');
        
        if (data) {
            id = data.split(':');
            window.open('http://' + location.host + '/framebar/bar/index/id/'+id[1]+'/url/'+$j.base64Encode($j(this).attr('href')), "mywindow","toolbar=0,menubar=0,directories=0,location=0,status=0,scrollbars=1,resizable=1");
        } else {
            window.open('http://' + location.host + '/framebar/bar/index/url/'+$j.base64Encode($j(this).attr('href')), "mywindow","toolbar=0,menubar=0,directories=0,location=0,status=0,scrollbars=1,resizable=1"); 
        }
        
        return false; 
     });
     
     $j("#fancybox-previous-browser-nav").click(function() {
        history.back();
        return false; 
     });
     
     $j("#fancybox-next-browser-nav").click(function() {
        history.forward();
        return false; 
     });
     
     $j(".open-new-window-if-possible").click(openInNewWindowIfPossible);
     
});
                                      
function getUrl(url, params) {
    var bpiParams = {};
    if ($j.query.get('bpi-embedded') && url.search(/bpi-embedded=/i)==-1) { bpiParams.embedded = $j.query.get('bpi-embedded');}
    if ($j.query.get('bpi-ref') && url.search(/bpi-ref=/i)==-1) { bpiParams.ref = $j.query.get('bpi-ref');}
    if ($j.query.get('bpi-history') && url.search(/bpi-history=/i)==-1) { bpiParams.history = $j.query.get('bpi-history');}
    
    var queryBpi = encodeQueryData(bpiParams, true)
    var queryParam = encodeQueryData(params, false);
    
    if(queryBpi.length>0 && queryParam.length>0) {
        return url += '?'+queryBpi+'&'+queryParam;
    } else if(queryBpi.length>0) {
        return url += '?'+queryBpi;
    } else if(queryParam.length>0) {
        return url += '?'+queryParam;
    }

    return url;
}

function encodeQueryData(data, namespace) {
   var ret = [];
   
   if (namespace) {
       for (var d in data) {
          ret.push("bpi-"+encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
       }
   } else {
       for (var d in data) {
          ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
       }    
   }
   
   return ret.join("&");
}

function addMessage(type, message) {
    if ($j('#messages').length>0) {
        $j('#messages').remove();
    }
    
    $j('#ajax-response-message').prepend('<ul class="messages" id="messages"><li class="'+type+'-msg"><ul><li>'+message+' Click <a href="" id="a-remove-msg">here</a> to continue.</li></ul></li></ul>');
    bindRemoveMessage($j('#a-remove-msg'));
}

function addMessages(messages) {
    if ($j('#messages').length>0) {
        $j('#messages').remove();
    }
    
    var text = '';
    for(i=0; i<messages.length; i++) {
        text += '<li class="'+messages[i].type+'-msg"><ul><li>'+messages[i].text+'</li></ul></li>';
    }
    
    $j('#ajax-response-message').prepend('<ul class="messages" id="messages">'+text+'</ul>');
    bindRemoveMessage($j('#a-remove-msg'));
}
        
function openInNewWindowIfPossible(){
    try{
        if(parent.window != window) {
            var data = $j(this).attr('data').split(';');
            var width = data[0].split(':')[1]; 
            var heigth = data[1].split(':')[1]; 
            
            var url;
            if ($j(this).attr('href')==undefined) {
                url = $j(this).parent().attr('href')        
            } else {
                url = $j(this).attr('href'); 
            }
            
            var name = "mywindow";
            if ($j(this).attr('name')!=undefined) {
                name = $j(this).attr('name');    
            }
            
            win = window.open(url,name,'scrollbars=1,width='+width+',height='+heigth);
            
            if ($j(this).hasClass('refresh-parent-on-close')) {
                var timer = setInterval(function() {   
                    if(win.closed) {  
                        clearInterval(timer);  
                        window.location.reload();  
                    }  
                }, 1000);
            }
            
            return false;
        }
    }  catch (e) {
    }
    
    return true;
}

function openFeedWindow(link) {
    var width = 615;
    var height = 500;
    var left = parseInt((screen.availWidth/2) - (width/2));
    var top = parseInt((screen.availHeight/2) - (height/2));
    var options = "width=" + width + ",height=" + height + ",status,scrollbars,left=" + left + ",top=" + top + "screenX=" + left + ",screenY=" + top + ",resizable=yes";
    window.open(link.href, "mywindow", options);
    return false;
}
