(function($) {
    $.fn.diablo3 = function() {
        var jQueryMatchedObj = this;
        
        this.hover(function() {
          $('div.skill-description').hide();
          //$(this).before("<div class='skill-description'>");
          if($(this).find('.skill-description').text() != '') {
              aDiv = $(this).find('.skill-description');
          } else {    
              $(this).css({ textDecoration:"underline" });
              $(this).css({ position:"relative"});
              $(this).append('<div class="skill-description" style="display:none;"></div>');
              aDiv = $(this).find('.skill-description');
          } 
          //$(this).append("<div class='skill-description'></div>");
          //aDiv = $(this).next("div");
          //aDiv = $(this).next("div.skill-description");
          aDiv.animate({opacity: "show", top: "-20"}, "fast");
          skillName = $(this).text();
          
          if(skillName == '') skillName = $(this).attr("skill");
          
          if(skillName == '' || skillName == undefined) skillName = $(this).attr("href");

          if(aDiv.text() == '') getSkill(aDiv, skillName,$(this).attr('id'));    
          
          }, function() {  
              aDiv.animate({opacity: "hide", top: "20"}, "fast");
              $(this).css({ textDecoration:"none" });
        });

        function _initialize() {
            _start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
            //return false; // Avoid the browser following the link
        }

        function _start(objClicked,jQueryMatchedObj) {

        }
        
        function getSkill(myObj, skillName, className) {
            contents = '';
            
            var urlSkillName = skillName.replace("'",'&#39;');
            url = '/d3api.php?request_type=skill&skill=' + skillName + '&class=' + className;
            
            $.getJSON(url, function(data) {     
                 runeData = '';
                 clvl = '';
                 if(data.type == 'passive') runeData = '<div class="skill-pop-runes">Passive Skill</div>';   
                 if(data.c_level > 0) clvl = '<div class="skill-pop-clvl en-clvl">Available at level ' + data.c_level + '</div>';
                 if(data.crimson != null) runeData = '<div class="skill-pop-runes"><span class="alabaster">' + data.alabaster + '</span> | <span class="crimson">' + data.crimson + '</span> | <span class="golden">' + data.golden + '</span> | <span class="indigo">' + data.indigo + '</span> | <span class="obsidian">' + data.obsidian + '</span></div>';  
                 
                 myObj.html('<table width="100%"><tr><td width="50"><img src="' + data.image_url + '"></td><td align="left" class="skill-pop-name">' + data.name + runeData + '</td></tr><tr><td colspan="2">'+ data.description + '</td></tr></table>' + clvl);
             
            });
            
            return true;
        }
                
        return this.unbind('click').click(_initialize);
    };
    
    $.fn.itemHover = function() {
        var jQueryMatchedObj = this;
        //give all the links a hidden div
          $('div.item-description').hide();
          
          //$(this).before("<div class='skill-description'>");
          if($(this).find('.item-description').text() != '') {
              aDiv = $(this).find('.item-description');
          } else {    
              //$(this).css({ textDecoration:"underline" });
              $(this).css({ position:"relative"});
              $(this).append('<div class="item-description" style="display:none;"></div>');
              aDiv = $(this).find('.item-description');
          } 
          
          
          
          if($(this).attr("pos") == 'left') {
              aDiv.css({left:'-430px'});
              aDiv.css({top:'100px'});
          }
        
        this.hover(function() {
          //$('div.item-description').hide();
          
          aDiv = $(this).find('.item-description');
          aDiv.animate({opacity: "show", top: aDiv.css('top')}, "fast");
          itemName = $(this).text();
          if(itemName == '' || itemName == undefined) itemName = $(this).attr("item")
          if(itemName == '' || itemName == undefined) itemName = $(this).attr("href");
          ;
          if(aDiv.text() == '') getItem(aDiv, itemName);    
          
          }, function() {
             //aDiv.animate({opacity: "hide", top: aDiv.css('top')}, "fast");
             aDiv.hide();
             $(this).css({ textDecoration:"none" });
          });

        function _initialize() {
            _start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
            //return false; // Avoid the browser following the link
        }

        function _start(objClicked,jQueryMatchedObj) {

        }
        
        function getItem(myObj, itemName) {
            contents = '';
            url = '/d3api.php?request_type=itemhtml&item=' + itemName;
            
            $.getJSON(url, function(data) {     
                 clvl = '';
  
                 //if(data.c_level > 0) clvl = '<div class="skill-pop-clvl en-clvl">Available at level ' + data.c_level + '</div>';
                 myObj.html(data.html);
             
            });
            
            return true;
        }
                
        return this.unbind('click').click(_initialize);
    };
    
    $.fn.streamSwitch = function() {
        var jQueryMatchedObj = this;
        
        
        function _initialize() {
             _start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
             var embedName = $(this).attr("title");
             var embedData = $('input.' + embedName).val();
            
             $('#stream-box').html(embedData);
             return false; // Avoid the browser following the link
        }

        function _start(objClicked,jQueryMatchedObj) {
            
        }
        
        return this.unbind('click').click(_initialize);
    };
    
    $.fn.updateSkill = function() {
        var jQueryMatchedObj = this;
        
        
        function _initialize() {
             _start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
             parentDiv = $(this);
             
            
             
             $('#skill-calc-popup-rune').hide();
             $('#skill-calc-popup-passive').hide();
             $('#skill-calc-popup-skill').show();
             
             slotId = $(this).parent().attr("id");

             $('a[name="skill-click"]').click(function(event) {
                 event.preventDefault();
                 skillName = $(this).attr("skill");
                 
                 className = $(this).attr("id");
                 parentDiv.find('.skill-calc-name').text(skillName.replace('/(<([^>]+)>)/ig',"")); 
                 iconDiv = parentDiv.parent().find('.skill-calc-icon');
                 iconDiv.html("<a href='" + skillName + "' id='" + className + "' class='skill'><img width='42' src='/icons/" + skillName + ".png'></a>"); 
                 iconDiv.find('a.skill').diablo3();
                 $('#skill-' + slotId + '-name').find('.skill-n').html(skillName.replace('/(<([^>]+)>)/ig',""));
                 $('#skill-' + slotId + '-text').find('.hidden-form').html("<textarea class='hidden' name='skill-" + slotId + "-name'>" + skillName.replace('/(<([^>]+)>)/ig',"") + "</textarea>");
                 $('#skill-calc-popup-skill').hide();
                 
                 parentDiv.parent().find('.skill-calc-rune').html('');
                });
             return false; // Avoid the browser following the link
        }

        function _start(objClicked,jQueryMatchedObj) {
            
        }
        
        return this.unbind('click').click(_initialize);

    };    
    
    $.fn.updatePassive = function() {
        var jQueryMatchedObj = this;
        
        function _initialize() {
             _start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
             $('#skill-calc-popup-rune').hide();
             $('#skill-calc-popup-passive').show();
             $('#skill-calc-popup-skill').hide();
             parentDiv = $(this);
             slotId = $(this).find('.skill-calc-passive').attr("id");

             $('a[name="passive-click"]').click(function(event) {
                 event.preventDefault();
                 skillName = $(this).attr("skill");
                 className = $(this).attr("id");
                 
                 iconDiv = parentDiv.find('.skill-calc-passive');
                 iconDiv.html("<a skill='" + skillName + "' href='#' id='" + className + "' class='skill'><img width='50' src='/icons/" + skillName + ".png'></a>"); 
                 iconDiv.find('a.skill').diablo3();
                 
                 $('#passive-' + slotId + '-name').find('.passive-n').html(skillName.replace('/(<([^>]+)>)/ig',""));
                 $('#passive-' + slotId + '-text').find('.hidden-form').html("<textarea class='hidden' name='passive-" + slotId + "-name'>" + skillName.replace('/(<([^>]+)>)/ig',"") + "</textarea>");
                 $('#skill-calc-popup-passive').hide();
                 
                 
                });
             return false; // Avoid the browser following the link
        }

        function _start(objClicked,jQueryMatchedObj) {
            
        }
        
        return this.unbind('click').click(_initialize);
    };
    
    $.fn.updateRune = function() {
        var jQueryMatchedObj = this;
        
        function _initialize() {
             _start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
             parentDiv = $(this);
             skillName = parentDiv.parent().find('.skill-calc-name').text();
             className = $('#skill-calc-head').text();
             
             url = '/d3api.php?request_type=runes&skill=' + skillName + '&class=' + className;
             slotId = $(this).parent().attr("id");
             
             if(parentDiv.parent().find('.skill-calc-name').text() != 'Choose Skill') {
             
                 $.getJSON(url, function(data) {     
                     runeData = '<a href="alabaster" class="srune-click"><div class="skill-calc-runel"><div class="icon-alabaster" style="float:left;"></div>' + data.alabaster + '</div></a>';
                     runeData += '<a href="crimson" class="srune-click"><div class="skill-calc-runel"><div class="icon-crimson"></div>' + data.crimson + '</div></a>';
                     runeData += '<a href="golden" class="srune-click"><div class="skill-calc-runel"><div class="icon-golden"></div>' + data.golden + '</div></a>';
                     runeData += '<a href="indigo" class="srune-click"><div class="skill-calc-runel"><div class="icon-indigo"></div>' + data.indigo + '</div></a>';
                     runeData += '<a href="obsidian" class="srune-click"><div class="skill-calc-runel"><div class="icon-obsidian"></div>' + data.obsidian + '</div></a>';
                     $('#skill-calc-popup-rune').html(runeData);
                 
                    $('.srune-click').click(function(event) {
                         event.preventDefault();
                         runeType = $(this).attr("href");
                         skillName = $(this).find('.rune-pop-name').text();
                        // parentDiv.find('.skill-calc-name').text(skillName.replace('/(<([^>]+)>)/ig',"")); 
                         //parentDiv.find('.skill-calc-rune').html('<'); 
                         className = $('#skill-calc-head').text();
                     
                         iconDiv = parentDiv.find('.skill-calc-rune');
                         iconDiv.html("<a href='" + skillName.replace("'",'&#39;') + "' id='" + className + "' class='skill'><div class='icon-" + runeType + "' style='margin:1px 0 0 2px;'></div></a>"); 
                         iconDiv.find('a.skill').diablo3();
                         
                         $('#skill-' + slotId + '-name').find('.skill-r').html(skillName.replace('/(<([^>]+)>)/ig',""));
                         $('#skill-' + slotId + '-name').find('.skill-r').addClass(runeType.replace('/(<([^>]+)>)/ig',""));
                         $('#skill-' + slotId + '-text').find('.hidden-form-r').html("<textarea class='hidden' name='rune-" + slotId + "-name'>" + skillName.replace('/(<([^>]+)>)/ig',"") + "</textarea>");
                         $('#skill-calc-popup-rune').hide();
                     });
                });
                 $('#skill-calc-popup-rune').show();
                 $('#skill-calc-popup-passive').hide();
                 $('#skill-calc-popup-skill').hide();
             }
             return false; // Avoid the browser following the link
        }

        function _start(objClicked,jQueryMatchedObj) {
            
        }
         
        return this.unbind('click').click(_initialize);
    };
    
    $.fn.itemSelect = function(animTo) {
        var jQueryMatchedObj = this;
        
        function _initialize() {
            _start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
            $('div.item-slot').css({border:"none"});
            console.log($(this).attr('style'));
            if( $(this).attr('status') == 'active') {
                $(this).css({border:"none"});
                $(this).attr('status','inactive');
                $('#item-list').animate({opacity: "hide", top: "0"}, "fast");
                return false;
            }
            $(this).css({border:"2px solid yellow"});
            $(this).attr('status','active');
            slot = $(this).attr("id").replace('slot-','');
            className = $('#skill-calc-head').text();
            rarity = 'Good';
            get_items(slot, rarity, className);
            return false; // Avoid the browser following the link
        }

        function _start(objClicked,jQueryMatchedObj) {
            //slot = objClicked.attr("id");
            //alert('Slot');
        }
        
        function get_items(slot, rarity, className)
        {
            url = '/d3api.php?request_type=items&slot=' + slot + '&class=' + className + '&rarity=' + rarity;

             $.getJSON(url, function(data) {  
                var ooe = 'even'; 
                var category = ucwords(slot);
                var itemList = '<table class="rows" style="width:375px;"><tr><th>cLvl</th><th id="list-slot" style="text-align:left;">' + category + '</th></tr>'; 
                
                $.each(data, function(i,aItem){
                    if(ooe == 'odd') {
                        ooe = 'even';
                    } else {
                        ooe = 'odd';
                    }
                    itemList = itemList + '<tr class="rows-' + ooe + '"><td style="text-align:center;">' + aItem.c_level + '</td><td><a set="' + aItem.set_name + '" class="item ' + aItem.rarity.toLowerCase() + '" id="' + aItem.image + '" itemid="' + aItem.id + '" hand="' + aItem.hand + '">' + aItem.name + '</a></td></tr>';
                });
                itemList = itemList + '</table>';
                $('#item-list').html(itemList);
                $('#item-list').animate({opacity: "show", top: animTo}, "fast");
                $('#item-list a.item').itemHover();
                $('a.item').click(function(event) {
                    //if this is a set item get set info
                    
                   
                    
                    
                    $('#item-list').hide();
                    $('#item-list').css({top: "-50"});
                    $(this).find('.item-description').remove();
                    itemName =  $(this).text();
                    itemImage = $(this).attr("id");
                    itemId = $(this).attr("itemid");
                    itemHand = $(this).attr("hand");
                    $('div.item-slot').css({border:"none"});
                    slotLink = $('#slot-'+slot).parent('a');
                    
                    //if they are replacing a 2 handed weapon
                    if(slotLink.attr('hand') == 2) {
                        if(slot == 'weapon') offCategory = 'offhand'; 
                        if(slot == 'offhand') offCategory = 'weapon'; 
                        $('#slot-'+offCategory).css({backgroundImage:'none'});
                        $('#effect-data div[slot="' + ucwords(offCategory) + '"]').remove();
                        slotLink.removeAttr('hand');
                        $('#slot-'+offCategory).parent('a').removeAttr('hand');
                    }
                    
                    
                    $('#slot-'+slot).css({backgroundImage:'url("/items/' + itemImage + '")'});
                    slotLink.attr('class','item');
                    slotLink.attr('item',itemName);
                    slotLink.find('.item-description').remove();
                    slotLink.itemHover();
                    slotLink.find('.item-description').css({left:'-430px'});
                    slotLink.find('.item-description').css({top:'100px'});
                    $('#slot-'+slot).attr('status','inactive');
                    
                    //if they are picking a 2 handed weapon
                    if(itemHand == 2) { 
                        slotLink.attr('hand','2')
                        if(slot == 'weapon') offCategory = 'offhand'; 
                        if(slot == 'offhand') offCategory = 'weapon'; 
                        slotLink = $('#slot-'+offCategory).parent('a');
                        $('#slot-'+offCategory).css({backgroundImage:'url("/items/' + itemImage + '")'});
                        slotLink.attr('class','item');
                        slotLink.attr('item',itemName);
                        slotLink.find('.item-description').remove();
                        slotLink.itemHover();
                        slotLink.find('.item-description').css({left:'-430px'});
                        slotLink.find('.item-description').css({top:'100px'});
                        $('#slot-'+offCategory).attr('status','inactive');
                        $('#effect-data div[slot="' + ucwords(offCategory) + '"]').remove();
                        slotLink.attr('hand','2');
                    } else {
                        slotLink.removeAttr('hand');
                    }
                    var setName = $(this).attr('set');
                    url = '/d3api.php?request_type=item_effects&item_id=' + itemId;
                    $.getJSON(url, function(eData) {  
                        //handle set bonuses
                        if(setName != '' )
                        {
                            $('#effect-data div[slot="' + category + '"]').remove();
                            setId = setName.replace(' ','');

                            if($('div#'+setId).length == 0)
                            {
                                url = '/d3api.php?request_type=set_effects&item=' + setName;
                                $.getJSON(url, function(sData) {  
                                    var setDiv = '<div id="'+setId+'" num="1">';
                                    
                                    $.each(sData, function(i,sEffect){
                                        setDiv = setDiv + '<div num="' + sEffect.num + '" id="' + sEffect.effect_key + '" class="' + sEffect.class_id + '" set="' + setName + '">' + sEffect.value + '</div>';
                                    });
                                    setDiv = setDiv + '</div>';
                                    $('#set-info').append(setDiv);
                                });
                            } else {
                                $('div#'+setId).attr('num', parseInt($('div#'+setId).attr('num')) + 1);
                            }
                            
                            $('#effect-data div[set="' + setId + '"]').remove();
                            var setChildren = $('div#'+setId).children();
                            $.each(setChildren, function(i,setChild){
                                var setValue = $(this);
                                //if the right number of set items are equpped then add the set bonuses to the effect data
                                if(parseInt($(this).attr('num')) <= parseInt($('div#'+setId).attr('num'))) $('#effect-data').append('<div id="' + $(this).attr('id') + '" class="' + $(this).attr('class') + '" slot="set" set="' + setId + '">' + $(this).text() + '</div>');
                           });
                        }
                        
                        
                        
                        
                        
                        $('#item-form-' + slot).find('.hidden-form').html("<input class='hidden' name='slot-" + slot + "' value='" + itemId + "'>");
                        
                        $.each(eData, function(i,aEffect){
                            $('#effect-data').append('<div id="' + aEffect.effect_key + '" class="' + aEffect.class_id + '" slot="' + category + '">' + aEffect.value + '</div>');
                        });
                        update_table();
                    });
                });
             });
        }
        
        function ucwords (str) {
            return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
                return $1.toUpperCase();
            });
        }

        function update_table() {
            var effects = new Array();
            var data = '';
           
            $("#effect-data").children().each(function(i) {
                var value = $(this).text();
                var effect_key = $(this).attr('id');
                var class_id = $(this).attr('class');
                var category = $(this).attr('slot');
                 
                //skip this one if it is APS on a weapon, add to TOTAL APS later
                if(category != 'Weapon' || effect_key != '{value} Attacks Per Second')
                {
                    
                    //set the array if we havnt yet
                    if(effects[effect_key] == undefined) effects[effect_key] = 0;
                    
                    value = value.replace('+','');
                    value = value.replace('%','');
                    
                    //check if this is a 
                    if(value.indexOf("-") == -1) {                    
                        effects[effect_key] = effects[effect_key] + parseInt(value);
                    } else {
                        if(effects[effect_key] == 0) {
                            effects[effect_key] = value;
                        } else {
                            effects[effect_key] = add_range(value, effects[effect_key]);
                        }
                    }
                }
            });
            
            $('#vitality-value').text(effects['{value} Vitality'] );
            $('#attack-value').text(effects['{value} Attack'] );
            $('#precision-value').text(effects['{value} Precision'] );
            $('#defense-value').text(effects['{value} Defense'] );
            var aps = add_range(effects['{value} Attacks Per Second'], effects['{value} Total APS']);
            $('#aps-value').text(aps);
            $('#castspeed-value').text(effects['{value} Casting Speed'] );
            $('#damage-value').text(effects['{value} Damage'] );
            $('#critp-value').text(effects['{value} Chance to Critical Hit'] );
            $('#critdmg-value').text(effects['{value} Critical Hit Damage'] );
            $('#attackerdmg-value').text(effects['Attackers Take {value} Damage'] );
            
            $('#block-value').text(effects['{value} Chance to Block'] );
            $('#life-value').text(effects['{value} Life'] );
            $('#lifeperhit-value').text(effects['Each Hit Adds {value} Life'] );
            $('#lifeperkill-value').text(effects['{value} Life After Each Kill'] );
            $('#liferegen-value').text(effects['Regenerates {value} Life per Second'] );
            
            $('#magicfind-value').text(effects['{value} Better Chance of Finding Magical Items'] );
            $('#goldfind-value').text(effects['{value} Gold From Monsters'] );
            $('#sockets-value').text(effects['{value} Total Sockets']);
            $('#randomprop-value').text(effects['{value} Random Propert(ies)(y)']);
            
            var allresists = effects['{value} Resistance to all elements'];
            $('#armor-value').html(effects['{value} Total Armor'].replace('-','<br /><span style="line-height:10px;">-</span><br />'));
            var dps = effects['{value} Total DPS'];

            $('#totaldps-value').text(dps);
            
            $('#poison-resist-value').text(add_range(effects['{value} Poison Resistance'],allresists));
            $('#lightning-resist-value').text(add_range(effects['{value} Lightning Resistance'],allresists));
            $('#arcane-resist-value').text(add_range(effects['{value} Arcane Resistance'],allresists));
            $('#cold-resist-value').text(add_range(effects['{value} Cold Resistance'],allresists));
            $('#fire-resist-value').text(add_range(effects['{value} Fire Resistance'],allresists));
        }
        
        function add_range(value, value2)
        {
            console.log("Adding Range(" + value + ', ' + value2 + ')');
            if(value == undefined) value = '0-0';
            if(value2 == undefined) value2 = '0-0';
            if(value.toString().indexOf('-') == -1) value = value + '-' + value;
            if(value2.toString().indexOf('-') == -1) value2 = value2 + '-' + value2;
            var numbers = new Array();
            numbers = value.split('-');
            var oNumbers = new Array();
            oNumbers = value2.split('-');
            oNumbers[0] = parseFloat(numbers[0]) + parseFloat(oNumbers[0]);
            oNumbers[1] = parseFloat(numbers[1]) + parseFloat(oNumbers[1]);
           
            var result =  roundNumber(oNumbers[0],2) + '-' + roundNumber(oNumbers[1],2);
            if(result == '0-0') {
                return '';
            } else {
                return result;
            }
        }
        function roundNumber(num, dec) {
            var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
            return result;
        }
        return this.unbind('click').click(_initialize);
    };
})(jQuery); 

