var cnt = 1;
var strNewHeight;
var strNewWidth;
var thisWidth;
var thisHeight;
var galStatus;
var objPopup;
var setPicHeight;
var PrevImg;
var NextImg;
var GalleryExists = false;
var MainGalleryExists = false;
var FirstImage = true;
var strMaxWidth = 243;
var FormSubmit = false;
var InvalidCode = false;
var strMediaExists = false;
var varOldFadeOut = 250;
var varHeightResize = 250;
var varNewFadeIn = 250;

$(function() {

    if (ResiBlogUpgrade) {
        $('.cornersBookmark').each(function(i) {
            $(this).bookmark({
                compact: true,
                addEmail: true,
                icons: 'images/bookmarks.png',
                addFavorite: true
            });
        });

        /* SOCIAL BOOKMARK PLUGIN SHOW ON HOVER .bookmarkIt */
        $('.bookmarkIt').hover(function() {
            var strThis = this.id;
            var offset = $('#ShareThisPost' + strThis).offset();
            $('#' + strThis + 'container').css('left', offset.left - 2).
            css('top', offset.top + $('#ShareThisPost' + strThis).height() - 2);
            $('#' + strThis + 'container').toggle();
        }, function() {
            var offset = $('.ShareThisPost').offset();

            var strThis = this.id;
            $('#' + strThis + 'container').css('left', offset.left - 2).
            css('top', offset.top + $('.ShareThisPost').height()) - 2;
            $('#' + strThis + 'container').toggle();
        });

        $('.GalleryControl,#FullScreen').hover(function() {
            $(this).addClass('LIHoverClass');
        }, function() {
            $(this).removeClass('LIHoverClass');
        });

        /* GALLERY NAVIGATION CONTROL CLICK TO ZOOM/ZOOMOUT */
        $('.Gallery img,#FullScreen').click(function() {
            thisWidth = (parseInt(arrWidth[cnt]) + parseInt(25));
            thisHeight = (parseInt(arrHeight[cnt]) + parseInt(25));
            strImage = $('#Image' + cnt).attr('src');
            if (objPopup) {
                objPopup.close();
            }
            objPopup = window.open(strImage, 'Image', 'resizable=no,scrollbars=no,width=' + thisWidth + ',height=' + thisHeight);
            objPopup.focus();
        });

        $('.GalleryControl').click(function() {
            strThisRel = $('#' + this.id).attr('rel');
            cnt = $('#Count').val();
            PrevImg = '#Image' + cnt;
            piccnt = $('#TotalCount').val();

            if (strThisRel != '-1') {
                $('#Count').val(parseInt(cnt) + parseInt(1));
                if (cnt == (parseInt(piccnt) + parseInt(1))) {
                    $('#Count').val(parseInt(1));
                    galStatus = 'Image ' + parseInt(1) + ' of ' + (parseInt(piccnt) + parseInt(1));
                    cnt = parseInt(1);
                } else {
                    $('#Count').val((parseInt(cnt) + parseInt(1)));
                    galStatus = 'Image ' + (parseInt(cnt) + parseInt(1)) + ' of ' + (parseInt(piccnt) + parseInt(1));
                    cnt = (parseInt(cnt) + parseInt(1));
                }
            } else {
                if (cnt == '1') {
                    $('#Count').val((parseInt(piccnt) + parseInt(1)));
                    galStatus = 'Image ' + (parseInt(piccnt) + parseInt(1)) + ' of ' + (parseInt(piccnt) + parseInt(1));
                    cnt = (parseInt(piccnt) + parseInt(1));
                } else {
                    $('#Count').val((parseInt(cnt) - parseInt(1)));
                    galStatus = 'Image ' + (parseInt(cnt) - parseInt(1)) + ' of ' + (parseInt(piccnt) + parseInt(1));
                    cnt = (parseInt(cnt) - parseInt(1));
                }
            }

            NextImg = '#Image' + cnt;

            ResizeWidth();
            $('.Gallery').height($('.GalleryContainer').height());

            $(PrevImg).fadeOut(varOldFadeOut, function() {
                $('.Gallery').animate({ height: thisHeight, queue: true, duration: varHeightResize }, function() {
                    $(PrevImg).toggleClass('DisabledPic');
                    $(NextImg).toggleClass('DisabledPic').css({
                        position: 'relative',
                        right: '0'
                    }).fadeIn(varNewFadeIn);
                    $('#PhotoGalleryImage').text(galStatus);
                });
            });
            return false;
        });


        $('.ArticlePhotoGallery li a').click(function() {
            PrevImg = '#Image' + cnt;
            cnt = parseInt($(this).attr('rel'));

            piccnt = $('#TotalCount').val();

            $('#Count').val(parseInt(cnt));
            galStatus = 'Image ' + parseInt(cnt) + ' of ' + (parseInt(piccnt) + parseInt(1));
            cnt = parseInt(cnt);

            NextImg = '#Image' + cnt;

            ResizeWidth();
            $('.Gallery').height($('.GalleryContainer').height());

            $(PrevImg).fadeOut(varOldFadeOut, function() {
                $('.Gallery').animate({ height: thisHeight, queue: true, duration: varHeightResize }, function() {
                    $(PrevImg).toggleClass('DisabledPic');
                    $(NextImg).toggleClass('DisabledPic').css({
                        position: 'relative',
                        right: '0'
                    }).fadeIn(varNewFadeIn);
                    $('#PhotoGalleryImage').text(galStatus);
                });
            });

            return false;
        });


    }

    //Configuration Options
    var max_width = MaxWidth; 	//Sets the max width, in pixels, for every image
    var selector = '.ImageResize * img'; 	//Sets the syntax for finding the images.  Defaults to all images.

    $(selector).each(function() {
        var width = $(this).width();
        var height = $(this).height();
        if (width > max_width) {
            //Set variables	for manipulation
            var ratio = (height / width);
            var new_width = max_width;
            var new_height = (new_width * ratio);

            //Shrink the image and add link to full-sized image
            $(this).height(new_height).width(new_width);

            $(this).hover(function() {
                $(this).attr('title', 'This image has been scaled down.\nClick to view the original image.')
                $(this).css('cursor', 'pointer');
            }, function() {
                //$(this).find('span:last').remove();
            });

            $(this).click(function() {
                strImage = $(this).attr('src');
                strTest = window.open(strImage, 'Image', 'resizable=no,scrollbars=no,width=' + (width + 25) + ',height=' + (height + 25));
            });

        }
    });

    $('#SearchForm').submit(function() {
        var SearchField = $('#search')
        if (SearchField.val() == '' || SearchField.attr('title') == SearchField.val()) {
            alert('Please enter a search criteria.');
            return false;
        } else {
            return true;
        }
    });

    if (FormSubmit) {
        /* FORM SUBMIT SCROLL TO BOTTOM TO THANK YOU DIV */
        destination = $('#CommentsTable').offset().top;
        $('html:not(:animated),body:not(:animated)').animate({ scrollTop: destination }, 1);
    } else {
        /* REPLACE FORM VALUE WITH TITLE FIELD FOR FORM HINTS ONLY IF FORM IS NOT SUBMITTED */
        $('input[title!=\'\'],textarea[title!=\'\']').hint();
    }

    if (InvalidCode) {
        /* FORM SUBMIT, ON INVALID CODE ALERT AND SCROLL TO BOTTOM */
        destination = $('.CommentSubmitForm').offset().top;
        $('html:not(:animated),body:not(:animated)').animate({ scrollTop: destination }, 1, "linear", function() {
            InvalidCodeAlert();
        });

    }

    if (GalleryExists) {
        setPicHeight = $('#Image1').height();
        ResizeWidth();
        ResizeRightPanelWidth();
    }

    if (strMediaExists) {
        //$('.media').media({ width: 400, height: 300, autoplay: true });

    }
    $('a.media').media().css('background-color','');
    $('.medialabel').toggle();
});

var invalidalert = true;
function InvalidCodeAlert() {
    if (invalidalert) {
        alert('You have entered the incorrect Captcha Security Code.\nPlease try again.');
        $('#SecurityCode').focus();
        invalidalert = false;
    }
}

function ResizeWidth() {
    try {
        thisWidth = arrWidth[cnt];
        thisHeight = arrHeight[cnt];
        if (thisWidth > MaxWidth) {
            $('#Image' + cnt).css({
                width: MaxWidth,
                height: thisHeight * MaxWidth / thisWidth
            });
        }

        thisWidth = $('#Image' + cnt).width();
        thisHeight = $('#Image' + cnt).height();

    } catch (ex) { alert(ex) }
}

//
//http://www.agentcasts.com/swfplayer/player_v1.swf?copy=true&video_id=HyhdQngUmt3Rbu6&vHeight=360&vWidth=480&autoplay=N
function GridPageResizeWidth(thisId) {
    try {
        $('#' + thisId + ' * img').each(function() {
            
            thisWidth = arrWidth[$('#' + thisId).attr('rel')];
            thisHeight = arrHeight[$('#' + thisId).attr('rel')];
            
            if (thisWidth > MaxWidth) {
                $(this).css({
                    width: MaxWidth,
                    height: thisHeight * MaxWidth / thisWidth
                });
               
            }

            thisWidth = $('#Image' + cnt).width();
            thisHeight = $('#Image' + cnt).height();
        });
    } catch (ex) { alert(ex) }
}
var strNewURL;
function GridPageResizeVideos(thisId) {
    return true;
}

function doanimate() {
    /*$(PrevImg).fadeOut(varOldFadeOut, function() {
        $('.Gallery').animate({ height: thisHeight, queue: true, duration: varHeightResize }, function() {
            $(PrevImg).toggleClass('DisabledPic');
            $(NextImg).toggleClass('DisabledPic').css({
                position: 'relative',
                right: '0'
            }).fadeIn(varNewFadeIn);
            $('#PhotoGalleryImage').text(galStatus);
        });
    });*/
}

function ResizeRightPanelWidth() {
    //try {
        $('.RightPanelContentPages img').each(function(i) {
            thisWidth = $(this).css('width').replace(/px/, '');
            thisHeight = $(this).css('height').replace(/px/, '');
            if (thisWidth > strMaxWidth) {
                $(this).css({
                    width: strMaxWidth,
                    height: thisHeight * strMaxWidth / thisWidth
                });
                thisWidth = $('#Image' + cnt).width();
                thisHeight = $('#Image' + cnt).height();
            }
        });
    ///} catch (ex) { alert(ex) }
}

function Left(str, n) {
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else
        return String(str).substring(0, n);
}

function DoCustomValidation() {
    var frm = document.getElementById('form');
    if (!(frm.Purchase_Type_Buy.checked) && !(frm.Purchase_Type.checked = false)) {
        alert('Please select a Purchase Type');
        frm.Purchase_Type_Buy.focus();
        return false;
    } else {
        return true;
    }
}

function RefreshImage(valImageId) {
    var objImage = document.images[valImageId];
    if (objImage == undefined) {
        return;
    }
    var now = new Date();
    objImage.src = objImage.src.split('?')[0] + '?x=' + now.toUTCString();
}

function toggleDiv(divId) {
    var div = document.getElementById(divId);
    if (div) {
        div.style.display = (div.style.display == 'none' ? 'block' : 'none');
    }
}

function ValidateSecurityCode() {
    var strFieldName = '#SecurityCode';
    var strCodeValue = $(strFieldName).val();
    var strCodeTitle = $(strFieldName).attr('title');

    if (strCodeValue == strCodeTitle) {
        alert(strCodeTitle);
        $(strFieldName).focus();
        return false;
    } else {
        return true;
    }

}

function toggleDiv(divId) {
    var div = document.getElementById(divId);
    if (div) {
        div.style.display = (div.style.display == 'none' ? 'block' : 'none');
    }
}

(function($) {
    $.fn.image = function(src, f) {
        return this.each(function() {
            var i = new Image();
            i.src = src;
            i.onload = f;
            this.appendChild(i);
        });
    }   

    $.fn.hint = function(blurClass) {
        if (!blurClass) blurClass = 'blur';

        return this.each(function() {
            var $input = $(this),
                title = $input.attr('title'),
                $form = $(this.form),
                $win = $(window);

            function remove() {
                if (this.value === title && $input.hasClass(blurClass)) {
                    $input.val('').removeClass(blurClass);
                }
            }

            // only apply logic if the element has the attribute
            if (title) {
                // on blur, set value to title attr if text is blank
                $input.blur(function() {
                    if (this.value === '') {
                        $input.val(title).addClass(blurClass);
                    }
                }).focus(remove).blur(); // now change all inputs to title

                // clear the pre-defined text when form is submitted
                $form.submit(remove);
                $win.unload(remove); // handles Firefox's autocomplete
            }
        });
    };


})(jQuery);

