/*
ProductDetail.js
Rich Reuter
Sogeti
rich.reuter@us.sogeti.com

This file contains all of the JavaScript used for the ProductDetailWebPart.
*/

// Need for IE 7 to pop the text up and make it visible
window.onload = function() {
    if (jQuery.browser.msie)
    {
        showTab(1);
    }
};

// Fix the image sizes/positions of the thumbnail images that are used to swap the large image.  
// If it's not a Mozilla based browser, we have to use a HTTP handler (ImageTag) in order to read the 
// file from disk and get the height and width.  We then insert the img tag that's returned into the DOM
// We have to do this because Non-Mozilla browsers don't always respect the image width and length when 
// the image is displayed - at least not reliably until everything is returned. This seems to be at least partially 
// caused by the number of things that are being sent back to the client, which sometimes slows things down.
jQuery(document).ready(function() {
    try
    {
        ResizeMainImage();

        jQuery('#sm_images img').each(function() {
            if (!jQuery.browser.mozilla)
            {
                var par = jQuery(this).parent();
                jQuery(this).remove();
                jQuery.get('ImageTag.axd?img=' + jQuery(this).attr('src') + '&type=small', function(data) {
                    var i = jQuery(data);  
                    jQuery(par).append(i);
                    try
                    {
                        jQuery(i).resizer({ width: 85, height: 85 });
                    } catch(inner) { };
                });
            }
            else
            {
                jQuery(this).resizer({ width: 85, height: 85 });
            }
        });
    } catch (err)
    {
        alert('Error: ' + err.description);
    }
});


// This section of code is to try to prevent a problem that kept cropping up with IE 7 where text would disappear 
// when the section was changed via the tabs and then the mouse moved off the tabs.  There's some sort of weird conflict 
// where a blank element would take precedence over the tabs and disappear.  Z-index changes in the CSS didn't seem to help.
// In truth, removing all of those events may not be entirely necessary, but this hack seems to work.
jQuery(document).ready(function() {

    try
    {
        if (jQuery.browser.msie)
        {
            var eventlist = [ 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave' ];
            for(var i = 0; i < eventlist.length; i++)
            {
                jQuery('.mainContent').unbind(eventlist[i]);
                jQuery('#product_images').unbind(eventlist[i]);
                jQuery('#product_images td').each(function() {
                    jQuery(this).unbind(eventlist[i]);
                });
            }
            
            jQuery('#p7tpb1_1').show();
            jQuery('#p7tpb1_1').css('z-index', '200');
        }

        // Set the height of the document to match the largest content
        ResizeMainContent();
    } catch (err)
    {
        alert('Error: ' + err.description);
    }
});

// Displays the specified content panel and hides the others
// Switches the styles up on the tabs to indicated which one
function showTab(indexID)
{
    var tabID = 'p7tpb1_' + indexID;
    var paneID = 'p7tpc1_' + indexID;
    
    var currentTab;
    var currentPane;

    for(var i = 1; i < 8; i++)
    {
        currentTab = '#p7tpb1_' + i;
        currentPane = '#p7tpc1_' + i;
        currentContentTD = '#content_' + i;
        
        jQuery(currentTab).removeClass();

        if (jQuery(currentTab).attr('id') == tabID)
        {
            if (i == 7)
            {
                jQuery(currentTab).addClass('how_to_buy_on');
            }
            else
            {
                jQuery(currentTab).addClass('down');
            }
            
            jQuery(currentPane).css('z-index', '200');

            // IE 7 hack to make sure that the content shows up correctly.  This is to correct an issue with the 
            // relative positioning.  Essentially, we remove the content and add it back
            var contentID = 'content_' + i;
            var jContentID = '#' + contentID;
            var x = jQuery(jContentID).html();
            jQuery(jContentID).html(x);

            if (jQuery.browser.msie)
            {
                jQuery(currentPane).css('height', '1%');
            }
            jQuery(currentPane).show();
        }
        else
        {
            if (i == 7)
            {
                jQuery(currentTab).addClass('how_to_buy_off');
            }
            else
            {
                jQuery(currentTab).addClass('tab');
            }
            jQuery(currentPane).hide();
            jQuery(currentPane).css('z-index', '198');
        }
    }
}

/* 
Swaps out the main image the image specified in the URL. This is called when a user clicks one of the 
small images on the page to display a larger image.
*/
function LargeImageSwap(newURL)
{
    try
    {
        // Set up the options
        var opts = { height: 445, width: 450 };
        
        // We create a new image to ensure that the height/width are correctly calculated
        var par = jQuery('#lg_img').parent();
        
        if (jQuery.browser.msie)
        {
            // Insert a temporary element to keep IE from failing to recognize the height 
            // of the containing div when we delete and add the image back in.
            jQuery(par).append('<span id="mm_tmp"><p>&nbsp;</p></span>');
            jQuery('#lg_img').remove();
            jQuery.get('ImageTag.axd?img=' + newURL, function(data) {
                var i = jQuery(data);  
                jQuery(par).append(i);
                jQuery(i).resizer(opts);
            });
            
            // Remove the temporary element
            jQuery('#mm_tmp').remove();
        }
        else
        {
            jQuery('#lg_img').remove();
            var i = jQuery('<img/>').attr('src', newURL).attr('id', 'lg_img');
            jQuery(par).append(i);
            jQuery(i).resizer(opts);
        }
    }
    catch(err)
    {
        alert('Error: ' + err.description);
    }    
 
}

/* 
Resizes the main image on the screen when the first image loads loads
*/
function ResizeMainImage()
{
    try
    {
        var opts = { height: 445, width: 450 };
        jQuery('#lg_img').resizer(opts);
    }
    catch(err)
    {
        alert('Error: ' + err.description);
    }
}

/** PANEL CODE **/
var pnlEmailPage;
var pnlAccessories;
var pnlProductImages;

// Show the email modal so that the user can send information about the page to someone else.
function ShowEmailPage()
{			
	pnlEmailPage = new Panel('EmailFormDisplay.axd?product_name=' + escape(jQuery('#product_name').val()) + 
     '&current_page=' + escape(jQuery('#current_page').val()), 'HideEmailPage', 500, 400, true, 0, 0, 0);
	pnlEmailPage.Show();
}

// Hide the email modal
function HideEmailPage()
{
	pnlEmailPage.Hide();
	delete pnlEmailPage;
}

// This method shows the popup where the user can browse through the list of available accessories.
function ShowAccessories(iProductID)
{
	pnlAccessories = new Panel('AccessoryImages.axd?ProductID=' + iProductID, 'HideAccessories', 800, 598, true, 0, 0, 0);
	pnlAccessories.Show();
}

// Close the accessories modal
function HideAccessories()
{
	pnlAccessories.Hide();
	delete pnlAccessories;
}

// This method shows the popup where the user can browse through the list of available product images.
function ShowProductImages(iProductID)
{
	pnlProductImages = new Panel('ProductImages.axd?ProductID=' + iProductID, 'HideProducts', 800, 598, true, 0, 0, 0);
	pnlProductImages.Show();
}

// Close the product images modal
function HideProducts()
{
	pnlProductImages.Hide();
	delete pnlProductImages;
}

/*
This function is invoked when the user uses the popup email modal to send a message about the product to 
another person.  This method first attempts to validate the form and make sure that all of the fields 
are filled out correctly.
*/
function EmailPage()
{
    if(jQuery('#txtFullName').val() == '')
    {
        jQuery('#txtFullName').css('border', '2px solid #FF0000'); 
    }
    else
    {
        if(IsEmail(jQuery('#txtFromEmail').val()) == false)
        {
	        jQuery('#txtFromEmail').css('border', '2px solid #FF0000'); 
        }
        else
        {
	        if(IsEmail(jQuery('#txtToEmail').val()) == false)
	        {
		        jQuery('#txtToEmail').css('border', '2px solid #FF0000'); 
	        }
	        else
	        {
	            // Make sure that the user cannot push the buttons twice and 
	            // send multiple emails
		        jQuery('#btnSubmit').attr('disabled', true);
		        jQuery('#btnReset').attr('disabled', true);
		        
		        // Create the AJAX call to the email processing handler, which is responsible for 
		        // sending the email and sending back a success/fail message.
                jQuery.post('ProcessEmail.axd', 
                    {
                        txtFullName: jQuery('#txtFullName').val(),
                        txtFromEmail: jQuery('#txtFromEmail').val(),
                        txtToEmail: jQuery('#txtToEmail').val(),
                        txComments: jQuery('#txComments').val(),
                        hdnProductName: jQuery('#hdnProductName').val(),
                        hdnProductLink: jQuery('#hdnProductLink').val()
                    },
                    function(msg) { 
                        jQuery('#Panel_Content_Page').html(msg);
                    } 
                );
	        }
        }
    }						
}

// Validate the email address
function IsEmail(strEmailAddress)
{
    // Declare Variables
    var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	
    // Test the e-mail address
    if (filter.test(strEmailAddress)) 
    {
        return true;
    }
    else 
    {
        return false;
    }
}

/* 
Set the height of the document to match the largest content in each of the tabs.  This function 
spins through all of the tabs, checks the height and attempts to match the height up with the largest 
section.
*/
function ResizeMainContent()
{
    var max_height = jQuery('.mainContent').height();
    jQuery('.p7TPcontent div').each(function() {
        if (jQuery(this).attr('id') != null && 
            jQuery(this).attr('id').indexOf('p7tpc') > -1)
        {
            if (jQuery(this).height() + 120 > max_height)
            {
                max_height = jQuery(this).height() + 120; // + 120 is to help provide the correct height;
            }
        }
    });
    
    // Make sure the content doesn't end up shorter than a certain minimum height.
    if (max_height < 660)
    {
        max_height = 660;
    }
    jQuery('.mainContent').height(max_height);
}