/*
 * jQuery ABBs Add-On
 *
 * Copyright (c) 2008 Dean Layton-James
 * Copyright (c) 2008 Digital Marmalade Ltd
 * Commercial License - Copying prohibited without express written permission
 *
 * $Date: 2008-07-01 08:22:17 GMT (Tue, 01 July 2008) $
 * $Rev: 68 $
 */

var $bErrorsOn = false ;

function JQABBsInit()
{
    // Standard jQuery wrapper
    $(document).ready(function() {
        // Make sure errors div is hidden when page loads
        if( !$bErrorsOn ) {
            $('#errors').hide();
        }
    });
}

function JQABBsAddError( errString )
{
    // alert( 'JQABBsAddError :: '+errString) ;
    // Standard jQuery wrapper
    $(document).ready(function() {
        // Add span to error div
        $("#errors").append('<p>' + errString + '</p>');
        // alert( 'JQABBsAddError2 :: '+errString) ;
        // show errors
        $('#errors').show('slow');
        // alert( 'JQABBsAddError3 :: '+errString) ;

        // set indicator that we have errors to show
        $bErrorsOn = true ;
        // fade it down
        // commented out, crashes in IE
        // $('#errors').vkfade('eee000');

    });
}


function JQABBsClearErrors( $iHide )
{
    // alert( 'JQABBsAddError :: '+errString) ;
    // Standard jQuery wrapper
    $(document).ready(function() {
        // clear error div
        $("#errors").empty();
        // hide div?
        if( $iHide ) {
            $('#errors').hide('slow');
        }

        // set indicator that we have no errors to show
        $bErrorsOn = false ;
    });
}


function JQABBsGetAJAXReturnValues( $sStr )
{
    var aInfo = $sStr.split('::') ;
    return aInfo ;
}

function JQABBsPreviewImage( sForm, sPreviewInput, sPreviewOutput, sDetailsHide )
{
    // Config block for the ajax submit
    //var aImgPreviewOptions = { url: '/admin-preview-upload.php', type: 'post', success: JQABBsSetPreviewImage } ;
    var aImgPreviewOptions = { url: '../admin-preview-upload.php', type: 'post', success: JQABBsSetPreviewImage } ;

    //ert( 'in JQABBsPreviewImage' ) ;

    // bind form using 'ajaxForm'
    $(document).ready(function() {

        //ert( 'set loading image to /_global/images/abbs/ajax-loader.gif' ) ;
        // set loading image
        // $('#' + sPreviewOutput).attr("src","/_global/images/abbs/ajax-loader.gif");
        $('#' + sPreviewOutput).attr("src","../_global/images/abbs/ajax-loader.gif");

      // requires field plugin
        // set previewInput field to let php script know which file field to handle
        $( "input[@name='previewInput']" ).setValue( sPreviewInput + '::' + sPreviewOutput );
        //alert( 'input[@name=previewInput setValue to ' + sPreviewInput + '::' + sPreviewOutput ) ;

        $('#' + sDetailsHide ).fadeOut();

		// requires form plugin
        // do an ajax submit
       //alert( 'ajax submit ') ;
        $( sForm ).ajaxSubmit( aImgPreviewOptions ) ;
        //alert( 'returning') ;

        return false ;
    } );
} // end function JQABBsPreviewImage

function JQABBsSetPreviewImage( imagePreviewInfo )
{
    // alert('JQABBsSetPreviewImage == ' + imagePreviewInfo) ;
    // Split the return data from the backend
    var aInfo = imagePreviewInfo.split('::') ;
    var sErr = 'An unkown error has ocurred' ;

    if( aInfo[0] == 'ERROR' ) {
        if( aInfo[1] == 'FILEUPLOAD' || aInfo[1] == 'FILEMOVE'  ) {
            sErr = 'Unable to preview the image' ;
        }
        if( aInfo[1] == 'FILESIZE' ) {
            sErr = 'The image is too large to upload or preview' ;
        }
        if( aInfo[1] == 'FILETYPE' ) {
            sErr = 'The file selected is not an image' ;
        }
        //$('#' + aInfo[1]).attr("src","/_global/images/abbs/preview_not_available.gif");
        $('#' + aInfo[1]).attr("src","../_global/images/abbs/preview_not_available.gif");
        JQABBsAddError( sErr ) ;
        // alert( 'ERRROR:: ' + sErr) ;
        return false ;
    }

    // alert( $('#' + aInfo[1]).attr("src","abbsimagepreview.php?pi=" + aInfo[0]) ) ;
    // alert( 'info 0 :: ' + aInfo[0]  ) ;
    // alert( 'info 1 :: ' + aInfo[1]  ) ;
    // set image source to tmp uploaded file
    //$('#' + aInfo[1]).attr("src","/abbsimagepreview.php?pi=" + aInfo[0]);
    $('#' + aInfo[1]).attr("src","../abbsimagepreview.php?pi=" + aInfo[0]);
    return false ;

} // end function JQABBsSetPreviewImage


function JQABBsPreviewSelectedImage(sField, sPreviewTag, sPath)
{
    // set default path
    if( sPath == '' ) {
        sPath = '../media/' ;
        // sPath = '/media/' ;
    } else {
        //alert( 'Got path :: ' +  sPath ) ;
    }
    sFilename =  $('#' + sField).val();
    //alert( sField + ' :: Got filename :: ' +  sFilename ) ;
    //alert( sField + ' :: Got Tag :: ' +  sPreviewTag ) ;
    if( $.trim(sFilename) != '' ) {
    //if( $.length(sFilename) > 0 ) {
        //alert( 'Setting' + '#' + sPreviewTag + ' To ' + sPath + sFilename ) ;
        $('#' + sPreviewTag).attr("src",sPath + sFilename);
    }

} // end function JQABBsPreviewSelectedImage


function JQABBsPreviewWaitingImage(sPreviewTag, sFilename, sPath)
{
    //alert( 'in JQABBsPreviewWaitingImage :: ' + sPreviewTag ) ;

    $(document).ready(function() {  
        // set default path
        if( sPath == '' ) {
            sPath = '../_suite_global/images/general/' ;
            //sPath = '/_suite_global/images/general/' ;
        } // end if
        // set default filename
        if( sFilename == '' ) {
            sFilename = 'icon_awaitingupload.gif' ;
        } 
        
        //alert( 'setting ' + sPreviewTag + ' to ' + '' + sPath + sFilename ) ;
        
        // alert( sField + ' :: Got filename :: ' +  sFilename ) ;
        if( $.trim(sFilename) != '' ) {
            $('#' + sPreviewTag).attr("src", '' + sPath + sFilename);
        } // end if
    }) ;

} // end function JQABBsPreviewWaitingImage


function JQABBsSetLabelIn( sSelector, sClass, sAttribute)
{
    $(document).ready(function(){
        if( sClass == '' ) {
            sClass = 'labelIn' ;
        }
        if( sAttribute == '' ) {
            sAttribute = 'name' ;
        }
    	$(sSelector).labelIn({li_class	: sClass, attribute : sAttribute});
    });
}


function JQABBsAddItemToJNiceSelect( $sSelector, $sVal, $sText)
{
    $(document).ready(function() {
    
        var $aaInfo = new Array() ;

        $aaInfo[$sVal] = $sText ;
        
        //alert( "selector " + $sSelector ) ;
        //alert( "$sVal " + $sVal ) ;
        //alert( "$sText " + $sText ) ;
        
        // Use select plugin to add option to hidden select
        $( $sSelector ).addOption($aaInfo, true); // use true if you want to select the added option
        $( $sSelector ).change(); 
        // Add to the jNice stuff
        $( $sSelector, this).each(function(index){
            // get the select
            var $select = $(this);        
            // get parent wrapper
            var $wrapper = $(this).parent() ;

            // deselect all jnice elements of the select
            $('a.selected', $wrapper).removeClass('selected');
            
            // find the jnice ul in the parent wrapper
            var $ul = $('ul', $wrapper);
            
            // get the number of items
            var $iSelectKount = $( $sSelector + ' option').size()  ;
            //alert( 'size is ' + $iSelectKount ) ;
            
            // add the new item to jNice select
            $ul.append('<li><a href="#" index="'+ ($iSelectKount - 1) +'" class="selected">'+ $aInfo[1] +'</a></li>');
            
            // Add new item to jNice display
            $('span', $wrapper).replaceWith('<span>'+$aInfo[1]+'</span>');            
            
        } ) ;
    } ) ; // end document ready
} // end function JQABBsAddItemToJNiceSelect


function JQABBsUploadSharedImage( sForm, sUploadInput, sUploadOutput, sDetailsHide )
{
    // Config block for the ajax submit
    // var aImgUploadOptions = { url: '/_suite_global/modules/core/admin-upload-shared-image.php', type: 'post', success: JQABBsSetUploadImage } ;
    var aImgUploadOptions = { url: '../_suite_global/modules/core/admin-upload-shared-image.php', type: 'post', success: JQABBsSetUploadImage } ;

    //alert( 'in JQABBsUploadSharedImage' ) ;
    //alert( 'in JQABBsUploadSharedImage2' ) ;

    // bind form using 'ajaxForm'
    $(document).ready(function() {

        // set loading image
        if( sUploadOutput != '' ) {
            ///alert( 'set loading image to /_global/images/abbs/ajax-loader.gif' ) ;
            // $('#' + sUploadOutput).attr("src","/_global/images/abbs/ajax-loader.gif");
            $('#' + sUploadOutput).attr("src","../_global/images/abbs/ajax-loader.gif");
        }

        // requires field plugin
        // set previewInput field to let php script know which file field to handle
        $( "input[@name='uploadInput']" ).setValue( sUploadInput + '::' + sUploadOutput );
        //alert( 'input[@name=uploadInput setValue to ' + sUploadInput + '::' + sUploadOutput ) ;

        if( sDetailsHide != '' ) {
            $('#' + sDetailsHide ).fadeOut();
            //alert( 'details hide ' );
        }

        // requires form plugin
        // do an ajax submit
        //alert( 'ajax submit ') ;
        $( sForm ).ajaxSubmit( aImgUploadOptions ) ;
        //alert( 'returning') ;

        return false ;
    } );
    
    //alert('doc not ready') ;
    //return false ;
} // end function JQABBsUploadSharedImage


function JQABBsSetUploadImage( imageUploadInfo )
{
    //alert( 'REturn :: ' + imageUploadInfo ) ;
    
    // Split the return data from the backend
    var aInfo = imageUploadInfo.split('::') ;
    var sErr = 'An unkown error has ocurred' ;

    if( aInfo[0] == 'ERROR' ) {
        if( aInfo[1] == 'FILEUPLOAD' || aInfo[1] == 'FILEMOVE'  ) {
            sErr = 'Unable to upload the image' ;
        }
        if( aInfo[1] == 'FILESIZE' ) {
            sErr = 'The image is too large to upload' ;
        }
        if( aInfo[1] == 'FILETYPE' ) {
            sErr = 'The file selected is not an image' ;
        }
        // $('#' + aInfo[1]).attr("src","/_global/images/abbs/preview_not_available.gif");
        $('#' + aInfo[1]).attr("src","../_global/images/abbs/preview_not_available.gif");
        JQABBsAddError( sErr ) ;
        return false ;
    }

    // Show upload message
    $('.' + aInfo[1]).show();
    // set image source to tmp uploaded file
    // $('#' + aInfo[1]).attr("src","/_global/images/abbs/preview_not_available.gif");
    return false ;

} // end function JQABBsSetUploadImage


function JQABBsUploadPromoSharedFile( sForm, sUploadInput, sUploadOutput, sDetailsHide )
{
    // Config block for the ajax submit
    // var aFileUploadOptions = { url: '/_suite_global/modules/core/admin-upload-promo-shared-File.php', type: 'post', success: JQABBsSetPromoUploadFile } ;
    var aFileUploadOptions = { url: '../_suite_global/modules/core/admin-upload-promo-shared-File.php', type: 'post', success: JQABBsSetPromoUploadFile } ;

    //alert( 'in JQABBsUploadPromoSharedFile' ) ;
    //alert( 'in JQABBsUploadSharedImage2' ) ;

    // bind form using 'ajaxForm'
    $(document).ready(function() {

        // set loading image
        if( sUploadOutput != '' ) {
            //alert( 'set loading image to /_global/images/abbs/ajax-loader.gif' ) ;
            //$('#' + sUploadOutput).attr("src","/_global/images/abbs/ajax-loader.gif");
            $('#' + sUploadOutput).attr("src","../_global/images/abbs/ajax-loader.gif");
        }

        // requires field plugin
        // set previewInput field to let php script know which file field to handle
        $( "input[@name='uploadInput']" ).setValue( sUploadInput + '::' + sUploadOutput );
        //alert( 'input[@name=uploadInput setValue to ' + sUploadInput + '::' + sUploadOutput ) ;

        if( sDetailsHide != '' ) {
            $('#' + sDetailsHide ).fadeOut();
            //alert( 'details hide ' );
        }

        // requires form plugin
        // do an ajax submit
        //alert( 'ajax submit ') ;
        $( sForm ).ajaxSubmit( aFileUploadOptions ) ;
        //alert( 'returning') ;

        return false ;
    } );
    
    //alert('doc not ready') ;
    //return false ;
} // end function JQABBsUploadSharedFile


function JQABBsSetPromoUploadFile( fileUploadInfo )
{
    //alert( 'REturn :: ' + fileUploadInfo ) ;
    
    // Split the return data from the backend
    var aInfo = fileUploadInfo.split('::') ;
    var sErr = 'An unkown error has ocurred' ;
    var s1 = aInfo[0] ;
    var aItem = { s1 : s1 } ;
        
    if( aInfo[0] == 'ERROR' ) {
        if( aInfo[1] == 'FILEUPLOAD' || aInfo[1] == 'FILEMOVE'  ) {
            sErr = 'Unable to upload the file' ;
        }
        if( aInfo[1] == 'FILESIZE' ) {
            sErr = 'The file is too large to upload' ;
        }
        if( aInfo[1] == 'FILETYPE' ) {
            sErr = 'The file selected is not an allowed filetype' ;
        }
        /// $('#' + aInfo[1]).attr("src","/_global/images/abbs/preview_not_available.gif");
        $('#' + aInfo[1]).attr("src","../_global/images/abbs/preview_not_available.gif");
        JQABBsAddError( sErr ) ;
        return false ;
    }

    // Show upload message
    $('.' + aInfo[1]).show();
    //JQABBsAddItemToJNiceSelect( '#promofile', aInfo[0], aInfo[0]) ;
    // $("#promofile").addOption([{aInfo[0]:aInfo[0]}], true);
    //alert( 'item :: '+aItem) ;
    $("#promofile").addOption(aItem, true);
    // set image source to tmp uploaded file
    // $('#' + aInfo[1]).attr("src","/_global/images/abbs/preview_not_available.gif");
    return false ;

} // end function JQABBsSetUploadFile


//function JQABBsDatePicker()
//{
//	// initialise the "Select date" link
//	$('#icon_calendar')
//		.datePicker(
//			// associate the link with a date picker
//			{
//				createButton:false,
//				startDate:'01/01/1997',
//				endDate:'31/12/2012'
//			}
//		).bind(
//			// when the link is clicked display the date picker
//			'click',
//			function()
//			{
//				updateSelects($(this).dpGetSelected()[0]);
//				$(this).dpDisplay();
//				return false;
//			}
//		).bind(
//			// when a date is selected update the SELECTs
//			'dateSelected',
//			function(e, selectedDate, $td, state)
//			{
//				updateSelects(selectedDate);
//			}
//		).bind(
//			'dpClosed',
//			function(e, selected)
//			{
//				updateSelects(selected[0]);
//			}
//		);
//
//	var updateSelects = function (selectedDate)
//	{
//		selectedDate = new Date(selectedDate);
//		var d = selectedDate.getDate();
//		var m = selectedDate.getMonth();
//		var y = selectedDate.getFullYear();
//		($('#formday')[0]).selectedIndex = d - 1;
//		($('#formmonth')[0]).selectedIndex = m;
//		($('#formyear')[0]).selectedIndex = y - 1997;
//	}
//	// listen for when the selects are changed and update the picker
//	$('#formday, #formmonth, #formyear')
//		.bind(
//			'change',
//			function()
//			{
//				var d = new Date(
//							$('#formyear').val(),
//							$('#formmonth').val()-1,
//							$('#formday').val()
//						);
//				$('#icon_calendar').dpSetSelected(d.asString());
//			}
//		);
//
//	// default the position of the selects to today
//	var today = new Date();
//	($('#formday')[0]).selectedIndex = today.getDate() - 1;
//	($('#formmonth')[0]).selectedIndex = today.getMonth();
//	($('#formyear')[0]).selectedIndex = today.getFullYear() - 1997;
//
//	// and update the datePicker to reflect it...
//	$('#formday').trigger('change');
//}
